classdef ApplyChangeHandler < handle
 % APPLYCHANGEHANDLER Handles changing the proposed data type from the
 % client and update the client after the backend is changed
 
 % Copyright 2016-2018 The MathWorks, Inc.
    
   properties (Access = private)
      Listener;
      Result;
      CollectedResults = [];
   end
    
   methods
       function this = ApplyChangeHandler(result)
           if ~isa(result, 'fxptds.AbstractResult')
               [msg, id] = fxptui.message('incorrectInputType','fxptds.AbstractResult',class(result));
               throw(MException(id, msg));
           end
          this.Listener = addlistener(result, 'UpdatedResultsOnProposedOrApplyChange', @(s, e)this.updateApplyResults);
          this.Result = result;
       end
       
       function processChange(this, clientData)
           % executes the change on the result and the DTGroup to change
           % whether the propose DT is to be accepted
           % once complete FPTEventHandler sends
           % 'UpdatedResultsOnProposedOrApplyChange' that is listened to by
           % the ApplyChangeHandler and executed in updateApplyResults
           this.Result.batchSetAccept(clientData.newValue);
       end
   end
   
   methods (Access = private)             
       function  updateApplyResults(this)
           % executed once the result has finalized change
           % the change can be on the result itself or on its DTGroup if it
           % belongs to one
           
           % Clear the listeners.
           for i = 1:numel(this.Listener)
               delete(this.Listener(i));
           end
           this.Listener = [];
           
           % get the FPT instance
           fptInstance = fxptui.FixedPointTool.getExistingInstance;
           
           if(isa(this.Result, 'fxptds.MATLABExpressionResult'))
               % updateData refreshes the entire set of data in
               % DataManager. it is a more expensive operation but is
               % necessary to get the all the changes made on a MLFB result
                fptInstance.getDataController.updateData('append', this.Result.getRunName);
           else
               % find all results in the same group based on this result
               groupResults = fxptds.Utils.getGroupResults(this.Result);
               
               % update the group's proposal
               fptInstance.getDataController.updateOnProposedDTChange([groupResults{:}]);
               
               % update result info for the current result
               fptInstance.getResultInfoController.publishDataForResult(this.Result);
           end
           
                
           % De-associate listeners and results after the processing is
           % done.
           this.Result = [];
       end
   end
end
