/*
 *  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.
 */
Ext.define('Ametys.plugins.odf.pilotage.helper.ExportHelper', {
    singleton: true,

    /**
     * @private
     * @property {Object} _OUTPUT_FORMATS The list of output formats
     */
    _OUTPUT_FORMATS: {
        "csv": "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXPORT_HELPER_OUTPUT_FORMAT_CSV}}",
        "xls": "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXPORT_HELPER_OUTPUT_FORMAT_XLS}}",
        "pdf": "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXPORT_HELPER_OUTPUT_FORMAT_PDF}}",
        "doc": "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXPORT_HELPER_OUTPUT_FORMAT_DOC}}"
    },

    /**
     * Choose the output formats to export
     * @param {String} title The dialog box title
     * @param {String} icon The dialog box icon
     * @param {String} exportURL The export URL
     * @param {Object} values The values to send to the export
     * @param {String[]} allowedOutputFormats The allowed output formats
     * @param {String} defaultOutputFormat The selected output format by default. Can be null to let the user select
     * @param {object} [additionalConfig] Additional configuration to add to the CFP
     * @param {String} [additionalConfig.additionalDescription] The optional additional description to add to the dialog box
     * @param {Object} [additionalConfig.additionalItems] The additionalItems to add to the CFP
     * @protected
     */
    export: function (title, icon, exportURL, values, allowedOutputFormats, defaultOutputFormat, additionalConfig)
    {
        additionalConfig = additionalConfig || {};

        let outputFormatEnumeration = [];
        for (let val in Ametys.plugins.odf.pilotage.helper.ExportHelper._OUTPUT_FORMATS)
        {
            if (!allowedOutputFormats.length || allowedOutputFormats.indexOf(val) > -1)
            {
                outputFormatEnumeration.push({
                    "value": val,
                    "label": Ametys.plugins.odf.pilotage.helper.ExportHelper._OUTPUT_FORMATS[val]
                });
            }
        }
        
        let formPanel = Ext.create('Ametys.form.ConfigurableFormPanel', {
            itemId: 'form',
            defaultFieldConfig: {
                labelWidth: 180
            },
            defaultPathSeparator: this._separator,
            scrollable: true,
            flex: 1
        });
        
        additionalConfig.additionalItems = additionalConfig.additionalItems || {};
        let formItems = Ext.merge(
            {},
            additionalConfig.additionalItems,
            {
                "outputFormat": {
                    label: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXPORT_HELPER_OUTPUT_FORMAT_TITLE}}",
                    description: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXPORT_HELPER_OUTPUT_FORMAT_DESC}}",
                    name: "outputFormat",
                    path: "outputFormat",
                    plugin: "odf-pilotage",
                    type: "string",
                    multiple: false,
                    hidden: allowedOutputFormats.length == 1,
                    "default-value": defaultOutputFormat,
                    enumeration: outputFormatEnumeration,
                    validation: {mandatory: true}
                }
            }
        );
        
        formPanel.configure(formItems);
        formPanel.setValues(); // setValues must always be called for configurable form panel in order to complete its initialization
        
        let description = "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXPORT_HELPER_DIALOG_HINT}}";
        if (additionalConfig.additionalDescription)
        {
            description += "<br/>" + additionalConfig.additionalDescription;
        }
        
        let dialogBox = Ext.create('Ametys.window.DialogBox', {
            title : title,
            iconCls : icon,
            width: 550,
            layout: {
                type: "vbox",
                align: "stretch"
            },
            defaultFocus: 'form',
            
            items: [{
                xtype: 'component',
                html: description
            }, formPanel],
            
            referenceHolder: true,
            defaultButton: 'validate',
            closeAction: 'destroy',
            
            buttons : [
                {
                    reference: 'validate',
                    text: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXPORT_HELPER_BUTTON_VALIDATE}}",
                    handler: validate,
                    scope: this
                }, {
                    text: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_EXPORT_HELPER_BUTTON_CANCEL}}",
                    handler: cancel
            }]
        });
        
        let hasOneVisible = formPanel.query("field[hidden=false]").length >= 1;
        if (hasOneVisible)
        {
            dialogBox.show();
        }
        else
        {
            submitForm(this);
        }
        
        function submitForm(context)
        {
            let formValues = formPanel.getValues();
            let valuesToSend = Ext.merge({}, values, formValues);
            context._export(exportURL, valuesToSend);
        }
        
        function validate(button)
        {
            if (formPanel.isValid())
            {
                submitForm(this);
                button.up('[xtype=dialog]').close();
            }
            else
            {
                let invalidFields = Ext.Array.filter(formPanel.getFieldNames(), function(fieldName) {
                    return !formPanel.getField(fieldName).isValid();
                });
                if (invalidFields.length > 0)
                {
                    formPanel.getField(invalidFields[0]).focus();
                }
            }
        }
        
        function cancel(button)
        {
            button.up('[xtype=dialog]').close();
        }
    },
    
    /**
     * Export to the given output format
     * @param {String} exportURL The export URL
     * @param {Object} values The values to send
     * @param {Object} outputFormat The output format
     * @private
     */
    _export: function(exportURL, values)
    {
        var appParameters = Ametys.getAppParameters();
        Ext.Object.each(appParameters, function(key, value) {
            values[key] = value;
        });
        
        Ametys.openWindow(`${exportURL}.${values["outputFormat"]}`, values);
    }
});