/*
 *  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 creating a dialog box to set properties for form mail.
 */
Ext.define('Ametys.plugins.forms.helper.FormMailDialogHelper', {
    singleton: true,
    
    /**
     * Open the dialog to create or edit the form mail dialog
     * @param {String} formId the id of the current form
     * @param {Object} initConfig The configuration object for initializing values
     * @param {Object} validConfig The configuration object for validating values
     * @param {Object} removeConfig The configuration object for removing values
     */
    open: function (formId, initConfig, validConfig, removeConfig)
    {
    	this._formId = formId;
    	this._validConfig = validConfig;
    	this._removeConfig = removeConfig;
        
    	this._delayedInitialize();
    	if (Ext.Object.isEmpty(removeConfig))
    	{
    		this._box.down('#remove').hide();
    	}
    	
    	if (!Ext.isEmpty(initConfig))
    	{
    		this._comboReceiver.getStore().addListener("load", function() 
            {
                initConfig.initFn(Ext.bind(this._initFormCb, this, [initConfig.title, initConfig.subject, initConfig.body], 1));
            }, this);
    		this._comboReceiver.getStore().load();
    	}
    },
    
	/**
	 * Initialize the dialogBox
     * @private
     */
	_delayedInitialize: function ()
	{
		if (this._initialized)
		{
			return;
		}
		
		this._comboReceiver = Ext.create('Ext.form.ComboBox', {
		    fieldLabel: '{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_RECEIVER}}',
		    ametysDescription: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_RECEIVER_DESC}}",
		    name: 'receiver',
			value: 'connected-user',
			store: this._getReceiverStore(),
		    queryMode: 'local',
		    displayField: 'title',
		    valueField: 'id'
		});
		
		this._form = Ext.create('Ext.form.Panel', {
			border: false,
			layout: 'anchor',
			width: window.innerWidth * 0.4,
			minWidth : 400,
			height: 350,
			scrollable: false,
			defaults:{
				xtype: 'textfield',
				labelAlign: 'top',
				labelSeparator: '',
				anchor: '100%'
			},
			items: [ 
				{
					name: 'sender',
					itemId: 'sender',
		        	fieldLabel: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_SENDER}}",
			        ametysDescription: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_SENDER_DESC}}"
		        },
		        this._comboReceiver,
		        {
		        	itemId: 'subject',
		        	name: 'subject',
		        	fieldLabel: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_SUBJECT}}",
			        ametysDescription: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_SUBJECT_DESC}}"
		        },
		        {
		        	itemId: 'body',
		        	name: 'body',
					xtype: 'textareafield',
					height: 150,
		        	fieldLabel: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_BODY}}",
			        ametysDescription: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_BODY_DESC}}"
		        }
			]
		});
		
		this._box = Ext.create('Ametys.window.DialogBox',  {
			title : "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_DIALOG_TITLE}}",
			iconCls : "ametysicon-envelope14",
			
			layout: 'fit',
			items : [{
						xtype: 'container',
						cls: 'a-text',
					  },
					  this._form 
			],
			
			closeAction: 'hide',
			
			referenceHolder: true,
			defaultButton: 'validate',
			
			buttons : [
                {
                    reference: 'validate',
                    text: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_DIALOG_OK_BTN}}",
                    handler: Ext.bind(this._ok, this)
                },
                {
                    text: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_DIALOG_CANCEL_BTN}}",
                    handler: Ext.bind(this._cancel, this)
                },
                {
                    itemId: 'remove',
                    text: "{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_DIALOG_REMOVE_BTN}}",
                    handler: Ext.bind(this._remove, this)
                }
            ]
		});
		
		this._initialized = true;
	},
	
	/**
	 * Callback for the form initialization process
	 * @param {Object} response the server's response
	 * @param {String} [response.sender] address of the sender for mail
	 * @param {String} [response.receiver] name-for-form of the field containing the email address of the receiver 
	 * @param {String} [response.subject] the subject of the mail,  
	 * @param {String} [response.body] the body of the mail,   
	 * @param {String} boxTitle the box title,  
     * @param {String} defaultSubject the default subject of the mail,  
     * @param {String} defaultBody the default body of the mail,   
	 * @private
     */
	_initFormCb: function(response, boxTitle, defaultSubject, defaultBody)
	{
		var sender = response.sender;
		var receiver = response.receiver;
		var subject = response.subject;
		var body = response.body;

		var form = this._form.getForm();
		form.findField('sender').setValue(!Ext.isEmpty(sender) ? sender : '');
		if (!Ext.isEmpty(receiver))
		{
			form.findField('receiver').setValue(receiver);
		}
		form.findField('subject').setValue(!Ext.isEmpty(subject) ? subject : defaultSubject);
		form.findField('body').setValue(!Ext.isEmpty(body) ? body : defaultBody);
		
		if (this._box.down('#remove') != null)
		{
			this._box.down('#remove').setDisabled(Ext.isEmpty(body));
		}
		
		this._box.setTitle(boxTitle);
		
		form.clearInvalid();
		this._box.show();
	},
	/**
	 * Handler invoked when the box's 'Cancel' button is clicked. Hides the box.
	 * @private
	 */
	_cancel: function ()
	{
		this._box.hide();
	}, 
	
	/**
	 * Get the receiver store 
	 * @private 
	 */
	_getReceiverStore : function()
	{
		return Ext.create('Ext.data.Store', {
		     proxy: {
		     	type: 'ametys',
		     	role: 'org.ametys.plugins.forms.helper.FormMailHelper',
                methodName: 'getAvailableReceiverFields',
                methodArguments: ['formId'],
                reader: {
                    type: 'json',
					rootProperty :'data'
                }
		     },
		     autoLoad: true,
		     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
        }));
    },
	
	/**
	 * Saving process
     * @private
	 */
	_ok: function ()
	{
		var form = this._form.getForm();
		if (!form.isValid())
		{
			return;
		}
		
		var sender = form.findField('sender').getValue();
		if (sender == '' || !/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,})$/.test(sender))
		{
			form.findField('sender').markInvalid ("{{i18n PLUGINS_FORMS_ACKNOWLEDGEMENT_RECEIPT_REGEX_ERROR}}");
			return;
		}
        if (Ext.isFunction(this._validConfig.validFn))
        {
    		var receiver = form.findField('receiver').getValue();
    		var subject = form.findField('subject').getValue();
    		var body = form.findField('body').getValue();
        	this._validConfig.validFn(sender, receiver, subject, body, Ext.bind(this._okCB, this));
        }
	},
	
	/**
     * Callback after validating the mail configuration
     * @private
     */
	_okCB: function ()
	{
        this._box.hide();
    },
    
    /**
     * Removing mail configuration
     * @private
     */
    _remove: function ()
    {
        if (!Ext.Object.isEmpty(this._removeConfig))
        {
            this._removeConfig.removeFn(Ext.bind(this._removeCB, this));   
        }
    },
    
    /**
     * Callback after removing the mail configuration
     * @private
     */
    _removeCB: function ()
    {
        this._box.hide();
    }
});