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

/**
 * Singleton helper class to open a dialog box for asking information before launching the execution of an asynchronous export.
 */
Ext.define('Ametys.plugins.cms.search.AsyncExportDialog', {
    singleton: true,
    
    /**
     * @private
     * @property {Ametys.window.DialogBox} _dialog The dialog box for asking information before launching the execution of the asynchronous export.
     */
    /**
     * @private
     * @property {Function} _serverCallFn The function to call when the form is valid AND the 'Ok' button is clicked
     */
    /**
     * @private
     * @property {Object} _scope The scope for the function
     */
    /**
     * @private
     * @property {Boolean} _validated The form is valid and can be send
     */
    
    /**
     * Opens the dialog box.
     * @param {Object} config The configuration
     * @param {Function} config.serverCallFn The function to call when the form is valid AND the 'Ok' button is clicked
     * @param {Object} config.serverCallFn.params The only function argument: all parameters
     * @param {String} config.serverCallFn.params.recipient The recipient filled by the user in this dialog box
     * @param {Object} config.scope The scope for the function
     */
    open: function(config)
    {
        this._serverCallFn = config.serverCallFn;
        this._scope = config.scope;
        if (this._dialog == null)
        {
            this._dialog = this._createDialogBox();
        }
        
        this._validated = false;
        this._initForm();
        this._dialog.show();
    },
    
    /**
     * Creates the dialog box
     * @return {Ametys.window.DialogBox} The dialog box
     * @private
     */
    _createDialogBox: function()
    {
        var formPanel = Ext.create('Ext.form.Panel', {
            itemId: 'form',
            border: false,
                     
            scrollable: false,
           
            defaults: {
                cls: 'ametys',
                labelSeparator: '',
                labelAlign: 'right',
                labelWidth: 60,
                anchor: '90%'
            },
            items: [
                {
                    xtype: 'component',
                    html: "{{i18n UITOOL_SEARCH_ASYNC_EXPORT_DIALOG_HINT}}",
                    cls: 'text'
                },
                {
                    xtype: 'textfield',
                    name: 'recipient',
                    fieldLabel: "{{i18n UITOOL_SEARCH_ASYNC_EXPORT_DIALOG_RECIPIENT_LABEL}}",
                    ametysDescription: "{{i18n UITOOL_SEARCH_ASYNC_EXPORT_DIALOG_RECIPIENT_DESC}}",
                    regex: /^.+\@.+$/,
                    regexText: "{{i18n UITOOL_SEARCH_ASYNC_EXPORT_DIALOG_RECIPIENT_INVALID_EMAIL}}"
                }
            ]
        });
        
        var dialog = Ext.create('Ametys.window.DialogBox', {
            layout: 'fit',
            
            title: "{{i18n UITOOL_SEARCH_ASYNC_EXPORT_DIALOG_TITLE}}",
            iconCls: 'ametysicon-play124 decorator-ametysicon-arrow-circle-right-double',
            
            width: 480,
            scrollable: false,
            
            items: [formPanel],
            
            closeAction: 'hide',
            buttons: [{
                text: "{{i18n UITOOL_SEARCH_ASYNC_EXPORT_DIALOG_BTN_OK}}",
                handler: this._ok,
                scope: this
            }, {
                text: "{{i18n UITOOL_SEARCH_ASYNC_EXPORT_DIALOG_BTN_CANCEL}}",
                handler: function() {
                    this._dialog.close();
                },
                scope: this
            }],
            
            listeners: {
                close: Ext.bind(this._onClose, this)
            }
        });
        
        return dialog;
    },
    
    /**
     * Initializes the form.
     * @private
     */
    _initForm: function()
    {
        var user = Ametys.getAppParameter('user');
        var form = this._dialog.items.getByKey('form').getForm();
        form.reset();
        form.findField('recipient').setValue(user && user.email || '' );
    },
    
    /**
     * The action to perform when the user clicks on the OK button from the dialog box.
     * @private
     */
    _ok: function()
    {
        var form = this._dialog.items.getByKey('form').getForm();

        var params = form.getValues();
            
        if (form.isValid())
        {
            this._validated = true;
            this._dialog.close();
        }
    }, 
    
    /**
     * @private
     * Listener when closing the dialog box
     */
    _onClose: function()
    {
        if (this._validated && this._serverCallFn)
        {
            var form = this._dialog.items.getByKey('form').getForm();
            var params = form.getValues();
            
            Ext.Function.defer (this._serverCallFn, 0, this._scope, [params]);
        }
        else
        {
            Ext.Function.defer (this._serverCallFn, 0, this._scope, [null]);
        }
    },
});