classdef ProposedDTChangeHandler < handle
    % PROPOSEDTCHANGEHANDLER 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;
    end
    
    methods
        function this = ProposedDTChangeHandler(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.updateProposeResults);
            this.Result = result;
        end
        
        function processChange(this, clientData)
            this.Result.batchSetProposedDT(clientData.newValue);
        end
    end
    
    methods (Access = private)
        function updateProposeResults(this)
            delete(this.Listener);
            this.Listener = [];
            
            % get the FPT instance
            fptInstance = fxptui.FixedPointTool.getExistingInstance;
            
            % 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);
            fptInstance.getExternalViewer.proposedTypeAnnotated(this.Result);
            
            % De-associate listeners and results after the processing is
            % done.
            this.Result = [];
        end
    end
end
