classdef RunsHandler
    % RUNSHANDLER manages the collect and verify runs
    
    % Copyright 2020 The MathWorks, Inc.
    
    methods(Hidden)
        function response = handle(~, clientData)
            % add response for the current workflow action
            response = struct;
            response.isSuccess = false;
            
            % get rid of ActionID field
            clientData = rmfield(clientData, 'ActionID');
            
            % get type of the results
            type = clientData.ResultType;
            
            % get instances of data layer and FPT
            fptInstance = fxptui.FixedPointTool.getExistingInstance();
            model = fptInstance.getModel;
            dataLayer = fxptds.DataLayerInterface.getInstance();              
            
            % get results for the current workflow
            currentWorkflow = dataLayer.getCurrentWorkflow(model); 
            results = dataLayer.getResultsByWorkflowID(model, currentWorkflow.ID, type);
            runNames = {};
            selectedRunIndex = -1;
            
            % for each result, extract run name
            for idx = 1:numel(results)
                result = results{idx};
                runNames{end+1} = result.RunName;  %#ok<AGROW>
                
                % keep track of the index of the last merged run
                if idx == numel(results)
                    selectedRunIndex = numel(runNames) - 1;
                end
                
                % extract scenario details if they exist
                if ~isempty(result.ScenarioResults)
                    for k = 1:numel(result.ScenarioResults)
                        scenario = result.ScenarioResults(k);
                        runNames{end+1} = scenario.RunName; %#ok<AGROW>
                    end
                end
            end
            
            % add the run names and status to the response
            response.runNames = runNames;
            response.selectedRunIndex = selectedRunIndex;
            response.isSuccess = true;
        end
    end
end

