/*
 *  Copyright 2023 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.
 */

/**
 * Helper to open a dialog box with date selection and comment for a step validation
 * @private
 */
Ext.define('Ametys.plugins.odf.pilotage.helper.ValidateDialog', {
	singleton: true,
	
    /**
     * Open dialog box with date and comment fields
     * @param {Object} config the dialog box configuration:
     * @param {String} config.dialogTitle The dialog title (required)
     * @param {String} config.dialogIconCls The css class for dialog icon (required)
     * @param {Function} config.validateCallback The callback function (required). The callback will be called with following arguments:
     * @param {String} config.validateCallback.date The date value
     * @param {String} config.validateCallback.comment The comment value
     * @param {String} [config.minDate] The minimum allowed date
     * @param {String} [config.minDateText] The error text to display when the date in is before the minDate
     * @param {String} [config.maxDate] The maximun allowed date
     * @param {String} [config.maxDateText] The error text to display when the date in is before the maxDate
     * @param {String} [config.dateValue] The date value to initialize the date field
	 * @param {String} [config.dateLabel] The label for the date field
     * @param {Boolean} [autoCloseDialog=true] Set to false to not close dialog after clicking on validate button
     * @return the dialog box
     */
	open: function (config)
    {
        config = Ext.applyIf(config, {
            autoCloseDialog: true
        });
        
        this._createDialog(config);
        
        this._form.setValues(); // setValues must always be called for configurable form panel in order to complete its initialization
        this._dialog.show();
        
        return this._dialog;
    },
    
    _createFormPanel: function (config)
    {
        var dateConfig = {value: config.dateValue};
        
        if (config.minDate)
        {
            dateConfig.minValue = config.minDate;
            if (dateConfig.minDateText)
            {
                dateConfig: config.minDateText + " (" +  Ext.Date.format(config.minDate, "d/m/Y") + ")"
            }
        }
        
        if (config.maxDate)
        {
            dateConfig.maxValue = config.maxDate;
            if (dateConfig.maxDateText)
            {
                dateConfig: config.maxDateText + " (" +  Ext.Date.format(config.maxDate, "d/m/Y") + ")"
            }
        }
        
		var formPanel = Ext.create('Ametys.form.ConfigurableFormPanel', {
            defaultFieldConfig: {
				labelSeparator: '',
                labelAlign: 'top',
                width: '100%',
                msgTarget: 'side'
            },
			bodyStyle: {
			    padding: '0 5px'
			},
            scrollable: false,
            flex: 1
        });
        formPanel.configure({
            "catalog": {
                label: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_HELPER_VALIDATION_DIALOG_CATALOG_LABEL}}",
                description: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_HELPER_VALIDATION_DIALOG_CATALOG_DESC}}",
                name: "catalog",
				validation: {
					mandatory: true
				},
                type: "STRING",
                "default-value": "CURRENT",
                widget: "edition.select-catalog",
				hidden: config.withCatalog !== true,
				disabled:  config.withCatalog !== true
            },
			"date": {
                label: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_HELPER_VALIDATION_DIALOG_DATE_LABEL}}",
                description: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_HELPER_VALIDATION_DIALOG_DATE_DESC}}",
                name: "date",
                type: "DATE",
				validation: {
					mandatory: true
				},
				"default-value": config.dateValue,
				"widget-params": dateConfig
            },
			"comment": {
				label: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_HELPER_VALIDATION_DIALOG_COMMENT_LABEL}}",
				description: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_HELPER_VALIDATION_DIALOG_COMMENT_DESC}}",
				widget: "edition.textarea",
				type: "STRING",
				name: 'comment'
			}
        });
		
		return formPanel;
    },
    
    _createDialog: function(config)
    {
        this._form = this._createFormPanel(config);
        
        var items = [];
        if (config.hintMsg)
        {
            items.push({
                xtype: 'component',
                cls: 'a-text',
                html: config.hintMsg,
				padding: '0 5 0 5'
            })
        }
        items.push(this._form);
        
        this._dialog = Ext.create('Ametys.window.DialogBox', {
            title: config.dialogTitle,
            iconCls: config.dialogIconCls,
            
            width: 450, 
            scrollable: false,
            
            items: items,
            
            referenceHolder: true,
            defaultButton: 'validate',
            closeAction: 'destroy',
            
            buttons: [{
                reference: 'validate',
                text: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_HELPER_VALIDATION_DIALOG_OK_BTN}}",
                handler: Ext.bind(this._validateFn, this, [config]),
                scope: this
            }, {
                text: "{{i18n plugin.odf-pilotage:PLUGINS_ODF_PILOTAGE_HELPER_VALIDATION_DIALOG_CANCEL_BTN}}",
                handler : function () { this._dialog.close()},
                scope: this
            }]    
        });
        
        return this._dialog;
    },
    
    _validateFn: function (config)
    {
        var form = this._form.getForm();
        if (!form.isValid())
        {
            return;
        }
        
        var values = form.getValues();
        
		if (config.withCatalog)
		{
			config.validateCallback(values.catalog, values.date, values.comment);
		}
        else
		{
			config.validateCallback(values.date, values.comment);
		}
        
        if (config.autoCloseDialog)
        {
            this._dialog.close();
        }
    }
});