/*
 *  Copyright 2022 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 for invite users to the form.
 */
Ext.define('Ametys.plugins.forms.helper.FormInvitationDialogHelper', {
    singleton: true,
    
//    statics: {
        openAccessTool: function()
        {
            var formTool = Ametys.tool.ToolsManager.getTool("uitool-profile-assignment-formsdirectoryaccess");
            if (formTool)
            {
                formTool.focus();
            }
            else
            {
                Ametys.tool.ToolsManager.openTool("uitool-profile-assignment-formsdirectoryaccess", {})
            }
        },
//    },
    
    /**
     * @private
     * @property {String} _formId The form id
     */
     
     /**
     * @private
     * @property {Integer} _nbUsers The number of users to invite
     */
    
    /**
     * Open the dialog to invite users to the form
     * @param {String} formId The form id
     */
    open: function (formId) 
    {
        this._formId = formId;
        
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.plugins.forms.helper.FormInvitationsHelper",
            methodName: "getNbOfUsersToInvite",
            parameters: [this._formId],
            callback: {
                handler: this._openCB,
                scope: this
            },
            waitMessage: true,
			errorMessage: true
        });
    },
    
    /**
     * Callback after getting users to invite
     * @param {Integer} nbUsers the nb of users to invite
     * @private
     */
    _openCB: function(nbUsers)
    {
        this._nbUsers = nbUsers;
        
        if (this._nbUsers == 0)
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_TITLE}}",
                msg: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_NO_USERS_TO_INVITE}}",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.WARNING
            });
        }
        else
        {
            this._invitationsDelayedInitialize();
            this._invitationsDialogBox.show();
            this._initInvitationsForm();
        }
    },
    
    /**
     * Initializes the dialog box for inviting users. 
     * @private
     */
    _invitationsDelayedInitialize: function()
    {
        if (!this._invitationsInitialized)
        {
            this._invitationsFormPanel = this._createInvitationsFormPanel();
            
            this._invitationsDialogBox = Ext.create('Ametys.window.DialogBox', {
                title: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_TITLE}}",
                iconCls: "ametysicon-envelope64",
                
                width: 500,
                scrollable: false,
                
                items: [this._invitationsFormPanel],
                
                defaultFocus: 'message',
                closeAction: 'hide',
                
                referenceHolder: true,
                defaultButton: 'validate',
                
                buttons: [{
                    reference: 'validate',
                    text: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_BUTTON_OK}}",
                    handler: Ext.bind(this._validateInvitations, this)
                }, {
                    text: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_BUTTON_CANCEL}}",
                    handler: Ext.bind(this._cancelInvitations, this)
                }]    
            });
            
            this._invitationsInitialized = true;
        }
    },
    
    /**
     * Creates the form panel of the invitation dialog box.
     * @return {Ext.form.Panel} The form panel
     * @private
     */
    _createInvitationsFormPanel: function()
    {
        let comboLanguage = Ametys.cms.language.LanguageDAO.createComboBox({
                name:'mailLanguage',
                itemId: 'form-admin-emails-dialog-languages',
                flex: 1,
                
                ametysDescription: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_LANGUAGE_HINT_DESC}}",
                
                synchronize: true
            });
                    
        var formPanel = Ext.create('Ext.form.Panel', {
            defaultType: 'component',
            defaults: {
                cls: 'ametys',
                labelSeparator: '',
                labelAlign: 'right',
                labelWidth: 70,
                width: '100%',
                msgTarget: 'side'
            },
            
            border: false,
            scrollable: false,
            
            items: [
                {
                    html: "",
                    cls: 'a-text',
                    name: 'hint-message',
                    itemId: 'hint-message'
                },
                {
                    cls: 'a-text',
                    html: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_LANGUAGE_HINT}}",
                },
                comboLanguage,
                {
                    cls: 'a-text',
                    html: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_MESSAGE_HINT}}",
                },
                {
                    xtype: 'textarea',
                    name: 'message',
                    itemId: 'message',
                    hideLabel: true,
                    fieldLabel: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_MESSAGE}}",
                    ametysDescription: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_MESSAGE_DESC}}",
                    height: 160,
                    allowBlank: false,
                    value: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_MESSAGE_DEFAULT}}"
                },
            ]
        });
        
        return formPanel;
    },
    
    /**
     * Initializes the invitations form.
     * @private
     */
    _initInvitationsForm: function()
    {
        var form = this._invitationsFormPanel.getForm();
        form.findField('message').setValue("{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_MESSAGE_DEFAULT}}");
        
        var hintField = this._invitationsFormPanel.items.findBy(function(e) { return e.itemId == 'hint-message'});
        
        var textHref = "<a href=javascript:void(0); onclick='Ametys.plugins.forms.helper.FormInvitationDialogHelper.openAccessTool()'>{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_HINT_HREF_TEXT}}</a>";
        var htmlText = Ext.String.format("{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_HINT}}", textHref, this._nbUsers);
        hintField.setHtml(htmlText);
    },
    
    _openLimitAccesTool: function()
    {
        var tool = Ametys.tool.ToolsManager.getTool('uitool-profile-assignment-formsdirectoryaccess');
        if (tool && !tool.hasFocus())
        {
            tool.focus();
        }
        else
        {
            Ametys.tool.ToolsManager.openTool('uitool-profile-assignment-formsdirectoryaccess', {});
        }
    },
    
    /**
     * @private
     * Handler for the 'ok' button of the invitation dialog box.
     */
    _validateInvitations: function()
    {
        var form = this._invitationsFormPanel.getForm();
        if (!form.isValid())
        {
            return;
        }
        
        var values = form.getValues();
        if (this._nbUsers > 20)
        {
            Ametys.Msg.confirm("{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_TITLE}}",
                    Ext.String.format("{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_SEND_WARNING}}", this._nbUsers), 
                    function(confirm) {
                        if (confirm == 'yes')
                        {
                            this._sendInvitation(values);
                        }
                    }, 
                    this
            );
        }
        else
        {
            this._sendInvitation(values);
        }
        
    },
    
    /**
     * @private
     * Send invitations
     * @param {Object} values The form values
     */
    _sendInvitation: function(values)
    {
        var params = [this._formId, values.message, Ametys.getAppParameter("siteName")];
        
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.plugins.forms.helper.FormInvitationsHelper",
            methodName: "sendInvitations",
            parameters: [this._formId, values.message, Ametys.getAppParameter("siteName"), values.mailLanguage],
            callback: {
                handler: this._validateInvitationsCb,
                scope: this
            },
            waitMessage: true,
			errorMessage: true
        });
    },
    
    /**
     * @private
     * Callback function after the invitations emails were sent.
     */
    _validateInvitationsCb: function()
    {
        Ametys.Msg.show({
            title: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_TITLE}}",
            msg: "{{i18n PLUGINS_FORMS_SEND_INVITATIONS_BOX_SUCCESS}}",
            buttons: Ext.Msg.OK,
            icon: Ext.MessageBox.INFO
        });
        this._invitationsDialogBox.close();
    },
    
    /**
     * @private
     * Callback for the "cancel" button of the invitation dialog box. Close it.
     */
    _cancelInvitations: function()
    {
        this._invitationsDialogBox.close();
    }
    
});