/*
 *  Copyright 2024 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * This class controls pilotage actions
 * @private
 */
Ext.define('Ametys.plugins.odf.pilotage.actions.PilotageActions', {
    singleton: true,
    
    /**
     * Opens the pilotage dashboard tool.
     */
    openDashboard: function()
    {
        Ametys.tool.ToolsManager.openTool('uitool-pilotage-dashboard-tool', {});
    },
    
    /**
     * Export derogations to CSV
     */
    derogations2CSV: function()
    {
        this._exportRules2CSV("derogation");
    },
    
    /**
     * Export additional rules to CSV
     */
    additionalRules2CSV: function()
    {
        this._exportRules2CSV("additional");
    },
    
    /**
     * Export complementary rules to CSV
     */
    complementaryRules2CSV: function()
    {
        this._exportRules2CSV("complementary");
    },
    
    /**
     * @private
     * Export rules of given type to CSV
     * @param {String} type The type of rules
     */
    _exportRules2CSV: function(type)
    {
        var tool = Ametys.tool.ToolsManager.getTool("uitool-pilotage-dashboard-tool");
        if (!tool)
        {
            return;
        }
            
        var values = {};
        values.type = type;
        values.catalog = tool._catalog;
        values.orgUnit = tool._orgUnit;
        
        var appParameters = Ametys.getAppParameters();
        Ext.Object.each(appParameters, function(key, value) {
            values[key] = value;
        });
        
        Ametys.openWindow(`${Ametys.getPluginDirectPrefix('odf-pilotage')}/rules/modifiedRules.csv`, values);
    },
    
    /**
     * Export MCC
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    exportMCC: function(controller)
    {
        let containerId = controller.getMatchingTargets()[0].getParameters().id;
        let values = {
            "reportId": "org.ametys.plugins.odfpilotage.report.MCCReport",
            "programItem": containerId,
        };
        
        let additionalConfig = {};
        
        if (controller.getInitialConfig('odf-skills-enabled') === 'true')
        {
            additionalConfig["additionalItems"] = {
                "mccMode": {
                    label: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_REPORT_SCHEDULER_PARAM_MCC_MODE_LABEL}}",
                    description: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_REPORT_SCHEDULER_PARAM_MCC_MODE_DESC}}",
                    name: "mccMode",
                    path: "mccMode",
                    plugin: "odf-pilotage",
                    "default-value": "main",
                    type: "string",
                    multiple: false,
                    enumeration: [
                        {
                            "value": "main",
                            "label": "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_REPORT_SCHEDULER_PARAM_MCC_MODE_VALUE_MAIN}}"
                        },
                        {
                            "value": "skills",
                            "label": "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_REPORT_SCHEDULER_PARAM_MCC_MODE_VALUE_SKILLS}}"
                        }
                    ],
                    "widget-params": {naturalOrder: true},
                    validation: {mandatory: true},
                    disableCondition: {
                        condition: [{
                            id: 'outputFormat',
                            operator: 'neq',
                            value: 'xls'
                        }]
                    }
                }
            };
        }
        
        Ametys.plugins.odf.pilotage.helper.ExportHelper.export(
            "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_CONTAINER_MCC_EXPORT_BUTTON_LABEL}}",
            "odficon-exam",
            `${Ametys.getPluginDirectPrefix('odf-pilotage')}/pilotage/report`,
            values,
            ['xls', 'doc', 'pdf'],
            'pdf',
            additionalConfig
        );
    },
    
    /**
     * Export Skills
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    exportElpCompetences: function(controller)
    {
        let programItem = controller.getMatchingTargets()[0].getParameters();
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.odf.ODFHelper",
            methodName: "getParentProgramEnumeration",
            parameters: [programItem.id],
            callback: {
                scope: this,
                handler: this._exportElpCompetencesCb,
                arguments: [programItem]
            },
            waitMessage: true,
            errorMessage: false
        });
    },
    
    _exportElpCompetencesCb: function(parentProgramValues, args)
    {
        let programItem = args[0];
        let values = {
            "reportId": "org.ametys.plugins.odfpilotage.report.ElpCompetencesExtract",
            "programItem": programItem.id
        };
        
        let additionalConfig = {
            "additionalDescription": Ext.String.format("{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_ELP_COMPETENCES_DIALOG_HINT}}", programItem.title)
        };
        
        if (parentProgramValues)
        {
            let parentProgramEnumeration = [];
            for (let val of parentProgramValues)
            {
                parentProgramEnumeration.push({
                    value: val.id,
                    label: val.title
                });
            }

            additionalConfig["additionalItems"] = {
                "program": {
                    label: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_REPORT_SCHEDULER_PARAM_PARENT_PROGAM_LABEL}}",
                    description: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_REPORT_SCHEDULER_PARAM_PARENT_PROGAM_DESC}}",
                    name: "program",
                    path: "program",
                    plugin: "odf-pilotage",
                    
                    hidden: parentProgramEnumeration.length == 1,
                    "default-value": parentProgramEnumeration.length == 1 ? parentProgramEnumeration[0].value : null,
                    type: "string",
                    multiple: false,
                    enumeration: parentProgramEnumeration,
                    validation: {mandatory: true}
                }
            };
        }
        
        Ametys.plugins.odf.pilotage.helper.ExportHelper.export(
            "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_CONTAINER_ELP_COMPETENCES_EXPORT_BUTTON_LABEL}}",
            "odficon-exam",
            `${Ametys.getPluginDirectPrefix('odf-pilotage')}/pilotage/report`,
            values,
            ['xls'],
            'xls',
            additionalConfig
        );
    },
    
    /**
     * Exclude the course from MCC
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    excludeFromMCC: function(controller, state)
    {
        var isExcluded = !state;
        var elpIds = isExcluded ? controller.getExcludedELPIds() : controller.getIncludedELPIds();
        
        if (!isExcluded)
        {
            var me = this;
            Ametys.Msg.confirm("{{i18n PLUGINS_ODF_PILOTAGE_EXCLUDED_FROM_MCC_CONFIRM_LABEL}}",
                "{{i18n PLUGINS_ODF_PILOTAGE_EXCLUDED_FROM_MCC_CONFIRM_MSG}}",
                function(answer)
                {
                    if (answer == 'yes')
                    {
                        me._setExcludedMCCState(elpIds, true);
                    }
                }
            );
        }
        else
        {
            this._setExcludedMCCState(elpIds, false);
        }
    },

    /**
     * @private
     * Will exclude or include from the MCC the ELPs registered by the controller.
     * @param {String[]} elpIds the ELP ids
     * @param {Boolean} isExcluded true if the ELPs are excluded from MCC
     */
    _setExcludedMCCState: function (elpIds, isExcluded)
    {
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.plugins.odfpilotage.helper.PilotageHelper",
            methodName: "setExcludedMCCState",
            parameters: [elpIds, isExcluded],
            callback: {
                scope: this,
                handler: this._setExcludedMCCStateCB,
                arguments: [isExcluded]
            },
            waitMessage: true,
            errorMessage: false
        });
    },
    
    /**
     * @private
     * Callback after exclude or include from the MCC the ELPs registered by the controller.
     * @param {Object} response the response
     * @param {Object} args the additional arguments
     */
    _setExcludedMCCStateCB: function(response, args)
    {
        if (response.noRightCourses.length)
        {
            var message = args[0] // is excluded
                ? Ametys.cms.content.ContentDAO._buildErrorMessage(message, response.noRightCourses, "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXCLUDED_FROM_MCC_ERROR_RIGHT_EXCLUDED_MSG}}<strong>", "</strong>")
                : Ametys.cms.content.ContentDAO._buildErrorMessage(message, response.noRightCourses, "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXCLUDED_FROM_MCC_ERROR_RIGHT_INCLUDED_MSG}}<strong>", "</strong>");
            
            Ametys.Msg.show({
                title: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXCLUDED_FROM_MCC_STATE_LABEL}}",
                msg: message,
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
        }
        
        if (response.alrightCourseIds.length)
        {
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.MODIFIED,
                parameters: {major: true},
                targets: {
                    id: Ametys.message.MessageTarget.CONTENT,
                    parameters: {
                        ids: response.alrightCourseIds
                    }
                }
            });
        }
    }
});