classdef ModelRenameStrategy < fxptds.WorkflowTopology.Strategy
    %% MODELRENAMESTRATEGY class
    % This strategy handles the model name changes when a model is saved as
    % a different name
    
    % Copyright 2018-2019 The MathWorks, Inc.
    
    properties(Dependent)
        TopModelRename
    end
    
    methods
        function value = get.TopModelRename(this)
            value = this.WorkflowContext.TopModelRename;
        end
    end
    
    % Access is protected and extended to Facade and to the test class
    methods (Access = {?fxptds.WorkflowTopology.Strategy, ?fxptds.WorkflowTopology.Facade, ?WorkflowTopologyTestCase})
        
        function execute(this)
            
            % validate existance of the node before continuing
            exists = this.Store.doesNodeExist(this.TopModel);
            if exists
                this.Store.rename(this.TopModel, this.TopModelRename);
                
                % Invalidate prepare nodes.
                prepareNodes = this.getNodesToInvalidate(); 
                this.invalidateNodes(prepareNodes);
                
                % get all the dependent node objects that are of the
                % collection type (simulate or derive)
                query = this.createDefaultQuery();
                query.Type = "Collection";
            
                collectionNames = this.executeQuery(this.TopModelRename, query);
                if numel(collectionNames) == 1 && isempty(collectionNames{1})
                    % if there are no depenendent collections, return early
                    return;
                end
                
                collectionObjects = this.Store.getNodeObject(collectionNames);
                
                % for each node, update the verification result with the
                % new top model name
                for node = collectionObjects'
                    %handle rename
                    report = node.Report;
                    report.TopModel = this.TopModelRename;
                    node.updateReport(report);
                end
            end
            
        end
    end
     methods (Access = {?fxptds.WorkflowTopology.Strategy, ?WorkflowTopologyTestCase})
        function nodesToInvalidate = getNodesToInvalidate(this)
            % Remove just the prepare node. 
            % get all the dependent node objects that are of the
            % prepare type 
            query = this.createDefaultQuery();
            query.Type = "Prepare";
            
            nodesToInvalidate = this.executeQuery(this.TopModelRename, query);
        end
        
     end   
end

