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

 Ext.define('Ametys.plugins.forms.entries.FormAdminEmailsDialog', {
	    singleton: true,
		
		/**
	     * Open the dialog box to configure the admin mails
	     * @param {Ametys.plugins.forms.controllers.LimitEntriesController} controller the controller calling this function
	     */
		act: function(controller)
		{
			var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
	        if (!target)
	        {
	            return;
	        }
	        
	        this._formId = target.getParameters().id;
	        this._formTitle = target.getParameters().title;
	        Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.forms.helper.FormAdminMailsHelper",
                methodName: "getAdminEmails",
                parameters: [this._formId],
                callback: {
                    handler: this._initFormCb,
                    scope: this
                },
                waitMessage: true,
                errorMessage: true
            });
		},
		
		/**
		 * @private
		 * Callback for the form initialization process
		 * @param {Object} response the server's response
		 * @param {String[]} response["admin-emails"] admin email addresses
		 * @param {String} response["admin-emails-other"] the receiver's field name
		 * @param {String} response["admin-email-subject"] the email's subject
		 * @param {String} response["admin-email-body"] the email's body
		 */
		_initFormCb: function(response)
		{
			this._delayedInitialize();
			var subject = response["admin-email-subject"];
			var body = response["admin-emails-body"];
			var receiver = response["admin-emails-other"];
			var defaultSubject = Ext.String.format("{{i18n PLUGINS_FORMS_ADMIN_EMAILS_SUBJECT_DEFAULT}}", this._formTitle);
			var defaultBody = Ext.String.format("{{i18n PLUGINS_FORMS_ADMIN_EMAILS_BODY_DEFAULT}}", this._formTitle);
			var form = this._form.getForm();
			var receiverField = form.findField('receiver');
			form.findField('emails').setValue(response["admin-emails"].join(', '));
			receiverField.getStore().load({
                callback: Ext.bind(function(){
                    receiverField.setValue(!Ext.isEmpty(receiver) ? receiver : null);
        			var toDisable = form.findField('emails').getValue() == "" && receiverField.getValue() == null;
                    this._box.down('#remove').setDisabled(toDisable);
                }, this)
            })
			
			form.findField('subject').setValue(!Ext.isEmpty(subject) ? subject : defaultSubject);
			form.findField('body').setValue(!Ext.isEmpty(body) ? body : defaultBody);
			form.clearInvalid();
			
			this._box.show();
		},
		
		/**
		 * Initialize the dialog box
		 */
		_delayedInitialize: function ()
		{
			if (this._initialized)
			{
				this._comboReceiver.getStore().load();
				return;
			}
			
			this._comboReceiver = Ext.create('Ext.form.ComboBox', {
                name: 'receiver',
                store: this._getReceiverStore(),
                queryMode: 'local',
                emptyText: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_RECEIVER_PLACEHOLDER}}",
                displayField: 'title',
                valueField: 'id',
                allowBlank: true,
                editable: false
            });
            
            this._comboLanguage = Ametys.cms.language.LanguageDAO.createComboBox({
                name:'mailLanguage',
                itemId: 'form-admin-emails-dialog-languages',
                fieldLabel: "{{i18n PLUGINS_FORMS_ADMIN_LANGUAGE_INPUT_LABEL}}",
                ametysDescription: "{{i18n PLUGINS_FORMS_ADMIN_LANGUAGE_INPUT_DESC}}",
                
                flex: 1,
                
                synchronize: true
            });
			
			this._form = Ext.create('Ext.form.Panel', {
				
				border: false,
				layout: 'anchor',
				width: window.innerWidth * 0.3,
				minWidth : 400,
				scrollable: true,
				submitEmptyText: false, 
				defaults:{
                    xtype: 'textfield',
                    labelAlign: 'top',
                    labelSeparator: '',
                    anchor: '100%'
                },
				items: [ 
					{
		                xtype: 'component',
		                cls: 'a-text',
	                    padding: '5',
		                html:"{{i18n PLUGINS_FORMS_ADMIN_EMAILS_INPUT}}"
		            },
                    this._comboLanguage,
					{
						name: 'emails',
						fieldLabel: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_INPUT_LABEL}}",
						emptyText: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_INPUT_PLACEHOLDER}}",
				        ametysDescription: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_INPUT_DESC}}"
			        },
			        this._comboReceiver,
                    {
                        itemId: 'subject',
                        name: 'subject',
                        fieldLabel: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_SUBJECT}}",
                        ametysDescription: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_SUBJECT_DESC}}",
                        allowBlank: false
                    },
                    {
                        itemId: 'body',
                        name: 'body',
                        xtype: 'textareafield',
                        height: 150,
                        fieldLabel: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_BODY}}",
                        ametysDescription: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_BODY_DESC}}",
                        allowBlank: false
                    },
                    {
                        xtype: 'component',
                        cls: 'a-text',
                        padding: '5',
                        html:"{{i18n PLUGINS_FORMS_ADMIN_EMAILS_INPUT_END}}"
                    }
				]
			});
	
			this._box = Ext.create('Ametys.window.DialogBox',  {
				
				title : "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_DIALOG_TITLE}}",
				iconCls : "ametysicon-desktop-envelope-close",
				
				layout: 'fit',
				items : [
					this._form 
				],
				
				defaultFocus: 'emails',
				closeAction: 'hide',
				
				referenceHolder: true,
				defaultButton: 'validate',
				
				buttons : [{
    					reference: 'validate',
    					text: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_DIALOG_OK_BTN}}",
    					handler: Ext.bind(this._ok, this)
    				}, {
    					text: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_DIALOG_CANCEL_BTN}}",
    					handler: Ext.bind(this._cancel, this)
    				},
    				 {
                        itemId: 'remove',
                        text: "{{i18n PLUGINS_FORMS_ADMIN_EMAILS_REMOVE_BTN}}",
                        handler: Ext.bind(this._remove, this)
                    } 
                ]
			});
			
			this._initialized = true;
		},
		
		/**
		 * @private
		 * Saving process
		 */
		_ok: function ()
		{
			var form = this._form.getForm();
			if (!form.isValid())
			{
				return;
			}
			
			var mails = form.findField('emails').getValue();
			var receiver = form.findField('receiver').getValue();
			if (mails && mails != "" || receiver && receiver != "")
			{
			    var mailsTab = mails.split(/[ ,;\r]/);
    			var error = false;
    			for (var i in mailsTab)
    			{
                    var mail = mailsTab[i].trim();
                    error = error || mail != '' && !(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,})$/.test(mail));
                }
    			if (!error)
    			{
                    var subject = form.findField('subject').getValue();
                    var body = form.findField('body').getValue();
                    var language = form.findField('mailLanguage').getValue();
                    
    				Ametys.data.ServerComm.callMethod({
                        role: "org.ametys.plugins.forms.helper.FormAdminMailsHelper",
                        methodName: "setAdminEmails",
                        parameters: [this._formId, mails, receiver, subject, body, language],
                        callback: {
                            handler: this._setAdminEmailsCb,
                            scope: this
                        },
                        waitMessage: true,
                        errorMessage: true
                    });
                    
                }
                else
                {
    				Ametys.Msg.show({
    					title: "{{i18n PLUGINS_FORMS_SET_ADMIN_EMAILS_ERROR_TITLE}}",
    					msg: "{{i18n PLUGINS_FORMS_SET_ADMIN_EMAILS_ERROR_MSG}}",
    				    buttons: Ext.Msg.OK,
    					icon: Ext.MessageBox.ERROR
    				});
    			}
            }
            else
            {
                Ametys.Msg.show({
                    title: "{{i18n PLUGINS_FORMS_SET_ADMIN_EMAILS_ERROR_TITLE}}",
                    msg: "{{i18n PLUGINS_FORMS_SET_ADMIN_EMAILS_ERROR_EMPTY_MSG}}",
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
            }
			
		},
		
		/**
         * Get the receiver store 
         * @private 
         */
        _getReceiverStore : function()
        {
            return Ext.create('Ext.data.Store', {
                 proxy: {
                    type: 'ametys',
                    role: 'org.ametys.plugins.forms.helper.FormMailHelper',
                    methodName: 'getAvailableAdminReceiverFields',
                    methodArguments: ['formId'],
                    reader: {
                        type: 'json',
                        rootProperty :'data'
                    }
                 },
                 autoLoad: false,
                 listeners: {
                        'beforeload': Ext.bind(this._onBeforeLoadReceiverStore, this)
                }
             });
        },
    	/**
         * Listens before loading the receiver store. 
         * @param {Ext.data.Store} store The store.
         * @param {Ext.data.operation.Operation} operation The Ext.data.operation.Operation object that will be passed to the Proxy to load the Store.
         * @private
         */
        _onBeforeLoadReceiverStore: function(store, operation)
        {
            operation.setParams( Ext.apply(operation.getParams() || {}, {
                formId: this._formId
            }));
        },
    
		/**
	     * @private
	     * Callback function called after setAdminEmails has been processed.
	     * @param {Object} response The text response provided by the {@link Ametys.data.ServerComm}
	     */
		_setAdminEmailsCb: function(response)
	    {
	    	if (response.message && response.message == 'invalid-address')
            {
                Ametys.Msg.show({
                    title: "{{i18n PLUGINS_FORMS_SET_ADMIN_EMAILS_ERROR_TITLE}}",
                    msg: "{{i18n PLUGINS_FORMS_SET_ADMIN_EMAILS_ERROR_MSG}}",
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
            }
            else
            {
                this._box.down('#remove').enable();
    	    	this._box.hide();
    	    	Ext.create("Ametys.message.Message", {
    	            type: Ametys.message.Message.MODIFIED,
    	            targets: {
    	                id: Ametys.message.MessageTarget.FORM_TARGET,
    	                parameters: {
    	                    id: this._formId,
    	                }
    	            }
    	        });
	        }
	     },
	     
	     /**
         * @private
         * Process for removing admin email
         */
        _remove: function ()
        {
            Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.forms.helper.FormAdminMailsHelper",
                methodName: "removeAdminEmails",
                parameters: [this._formId],
                callback: {
                    handler: this._unsetAdminEmailsCb,
                    scope: this,
                },
                waitMessage: true,
                errorMessage: true
            });
        },
        
        /**
         * @private
         * Callback function called after removeAdminEmails has been processed.
         */
        _unsetAdminEmailsCb: function()
        {
            this._box.down('#remove').setDisabled(true);
            this._box.hide();
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.MODIFIED,
                targets: {
                    id: Ametys.message.MessageTarget.FORM_TARGET,
                    parameters: {
                        id: this._formId,
                    }
                }
            });
        },
	     
		/**
		 * @private
		 * Handler invoked when the box's 'Cancel' button is clicked. Hides the box.
		 */
		_cancel: function ()
		{
			this._box.hide();
		}
	});