classdef OptimizeAction < fxptui.internal.action.Action
    %OPTIMIZEACTION Action of converting a model using fxpopt

    %   Copyright 2019-2022 The MathWorks, Inc.

    methods(Access = {?fxptui.internal.action.Action, ?WorkflowTestCase})

        function executeLocal(~, optimizationEngine, workflowSetting)

            % extract the TopModel information from the DesignSetting
            designSettings = workflowSetting.getSettingValue('DesignSetting');
            topModel = designSettings.TopModel;
            sud = designSettings.SelectedSystemToScale;

            % convert the fxpopt Baseline run into a FPTRunID
            dataLayer = fxptds.DataLayerInterface.getInstance();
            [~, baselineRunID] = dataLayer.getIdFromRunName(topModel, DataTypeOptimization.BaselineProperties.RunName);

            % create a context for invalidating any prior nodes associated
            % with optimization action
            context = fxptds.WorkflowTopology.WorkflowContextFactory.getContext(fxptds.UserIntent.StartOptimization, ...
                'FPTRunID', baselineRunID);
            facade = dataLayer.getWorkflowTopologyFacade(topModel);

            % register the intent
            facade.register(context);

            % handle unsupported blocks
            optimizationOptions = workflowSetting.getSettingValue('OptimizationSetting');
            [unsupportedHandler, unsupportedBlocksExist] = fxptui.internal.utils.Utils.checkUnsupportedBlocks(topModel, sud, optimizationOptions);
            if unsupportedBlocksExist
                unsupportedHandler.handleUnsupported(optimizationOptions);
            end

            % run the optimization
            result = optimizationEngine.run();

            % get the current Workflow ID
            currentWorkflow = dataLayer.getCurrentWorkflow(topModel);
            currentWorkflowID = currentWorkflow.ID;
            currentWorkflowIntent = currentWorkflow.WorkflowIntent;

            % construct a depot unit
            depotUnit = fxptds.internal.workflow.depot.WorkflowDepotUnit;
            depotUnit = depotUnit.setID(currentWorkflowID);
            depotUnit = depotUnit.setIntent(currentWorkflowIntent);
            depotUnit = depotUnit.setResult(result);

            % add the depot unit to dataset
            dataLayer.addDepotUnit(topModel, depotUnit);

        end

    end

end

% LocalWords:  FPT
