/*
 *  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.LimitEntriesDialog', {
	    singleton: true,
		
		/**
	     * Open the dialog box to limit number of entries
	     * @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._delayedInitialize(controller);
			
			// Init form with the first selection
			this._initForm();
		},
		
		/**
		 * Initialize the form with values provided by the server
		 * @private
		 */
		_initForm: function ()
		{
			Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.forms.helper.LimitedEntriesHelper",
                methodName: "getLimitedEntriesProperties",
                parameters: [this._formId],
                callback: {
                    handler: this._initFormCb,
                    scope: this,
                    arguments: {}
                },
                waitMessage: true,
                errorMessage: true
            });
		},
		
		/**
		 * Callback for the form initialization process
		 * @param {Object} response the server's response
		 * @private
		 */
		_initFormCb: function(response)
		{
			var limitToOneEntryByUser = response['limit-to-one-entry-by-user'];
			var limitEntries = response['limit-entries-enabled'];
            var maxEntriesNb = response['max-entries'];
			var remainingDisplayMsg = response['remaining-message'];
			var closedFormMsg = response['closed-message'];
			var queueEnabled = response['queue-enabled'];
			var queueSize = response['queue-size'];
			var closedFormQueueMsg = response['queue-closed-message'];
			this._queueMsgSender = response['queue-sender'];
			this._queueMsgReceiver = response['queue-receiver'];
			this._queueMsgSubject = response['queue-subject'] ||"{{i18n PLUGINS_FORMS_QUEUE_SUBJECT_DEFAULT}}";
			this._queueMsgBody = response['queue-body'] || "{{i18n PLUGINS_FORMS_QUEUE_BODY_DEFAULT}}";
	
			var form = this._form.getForm();
			form.findField('limit-to-one-entry-by-user').setValue(!Ext.isEmpty(limitToOneEntryByUser) ? limitToOneEntryByUser : false);
			form.findField('limit-entries-enabled').setValue(!Ext.isEmpty(limitEntries) ? limitEntries : false);
			form.findField('max-entries').setValue(!Ext.isEmpty(maxEntriesNb) ? maxEntriesNb : 10);
			form.findField('remaining-message').setValue(!Ext.isEmpty(remainingDisplayMsg) ? remainingDisplayMsg : "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_REMAINING_DISPLAY_MESSAGE_DEFAULT}}");
			form.findField('closed-message').setValue(!Ext.isEmpty(closedFormMsg) ? closedFormMsg : "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_CLOSED_DISPLAY_MESSAGE_DEFAULT}}");
			
			var isLimited = form.findField('limit-entries-enabled').getValue();
			form.findField('max-entries').setDisabled(!isLimited);
			form.findField('remaining-message').setDisabled(!isLimited);
			form.findField('closed-message').setDisabled(!isLimited);
			form.findField('queue-enabled').setDisabled(!isLimited);
			
			form.findField('queue-enabled').setValue(queueEnabled);
			if (!Ext.isEmpty(queueSize))
			{
				form.findField('queue-size').setValue(queueSize);
			}
			form.findField('queue-closed-message').setValue(!Ext.isEmpty(closedFormQueueMsg) ? closedFormQueueMsg : "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_CLOSED_QUEUE_MSG_DEFAULT}}");
			
			var isQueueEnabled = form.findField('queue-enabled').getValue();
			form.findField('queue-size').setDisabled(!isLimited || isLimited && !isQueueEnabled);
			form.findField('queue-closed-message').setDisabled(!isLimited || isLimited && !isQueueEnabled);
			this._box.down('#personalizeQueue').setDisabled(!isLimited || isLimited && !isQueueEnabled);
            
			form.clearInvalid();
			this._box.show();
		},
		
		/**
		 * Initialize the form with values provided by the server
		 * @private
		 */
		_delayedInitialize: function ()
		{
			if (this._initialized)
			{
				return;
			}
			
			this._form = Ext.create('Ext.form.Panel', {
				
				border: false,
				layout: 'anchor',
				width: window.innerWidth * 0.3,
				minWidth : 400,
				scrollable: true,
				defaults:{
					labelAlign: 'top',
					anchor: '100%',
                    labelSeparator: ''
				},
				
				items: [ 
					{
						name: 'limit-to-one-entry-by-user',
						xtype: 'checkboxfield',
			        	boxLabel: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_UNIQUE_ENTRY}}",
				        ametysDescription: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_UNIQUE_ENTRY_DESC}}"
			        },
					{
						name: 'limit-entries-enabled',
						xtype: 'checkboxfield',
			        	boxLabel: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_ENABLE}}",
				        ametysDescription: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_ENABLE_DESC}}"
			        },
					{
						name: 'max-entries',
						itemId: 'max-entries',
						xtype: 'numberfield',
						allowBlank: false,
						margin: '0 0 0 30',
			        	fieldLabel: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_MAX_NUMBER}} *",
				        ametysDescription: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_MAX_NUMBER_DESC}}"
			        },
			        {
			        	itemId: 'remaining-message',
			        	name: 'remaining-message',
			        	margin: '0 0 0 30',
			        	xtype: 'textareafield',
			        	fieldLabel: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_REMAINING_DISPLAY_MESSAGE}}",
				        ametysDescription: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_REMAINING_DISPLAY_MESSAGE_DESC}}"
			        },
			        {
			        	itemId: 'closed-message',
			        	name: 'closed-message',
			        	margin: '0 0 10 30',
			        	xtype: 'textareafield',
			        	fieldLabel: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_CLOSED_DISPLAY_MESSAGE}}",
				        ametysDescription: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_CLOSED_DISPLAY_MESSAGE_DESC}}"
			        },
					{
						name: 'queue-enabled',
						xtype: 'checkboxfield',
						margin: '0 0 0 30',
			        	boxLabel: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_ENABLE_QUEUE}}",
				        ametysDescription: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_ENABLE_QUEUE_DESC}}"
			        },
			        {
                        name: 'queue-closed-message',
                        margin: '0 0 0 60',
                        xtype: 'textareafield',
                        fieldLabel: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_CLOSED_QUEUE_MSG}}",
                        ametysDescription: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_CLOSED_QUEUE_MSG_DESC}}"
                    },
					{
						name: 'queue-size',
						xtype: 'numberfield',
						margin: '0 0 10 60',
			        	fieldLabel: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_QUEUE_SIZE}}",
				        ametysDescription: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_QUEUE_SIZE_DESC}}"
			        },
					{
						itemId: 'personalizeQueue',
						xtype: 'button',
						anchor: '40%',
						margin: '0 0 10 60',
						text:"{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_QUEUE_MAIL_EDITION}}",
						handler: this._openQueueMessageDialog,
						scope: this
			        }
				]
			});
	
			this._box = Ext.create('Ametys.window.DialogBox',  {
				
				title : "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_DIALOG_TITLE}}",
				iconCls : "ametysicon-transport10",
				
				layout: 'fit',
				items : [{
							xtype: 'container',
							cls: 'a-text',
						  },
						  this._form 
				],
				
				defaultFocus: 'limit-to-one-entry-by-user',
				closeAction: 'hide',
				
				referenceHolder: true,
				defaultButton: 'validate',
				
				buttons : [{
					reference: 'validate',
					text: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_DIALOG_OK_BTN}}",
					handler: Ext.bind(this._ok, this)
				}, {
					text: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_DIALOG_CANCEL_BTN}}",
					handler: Ext.bind(this._cancel, this)
				} ]
			});
			
			this._form.getForm().findField("limit-entries-enabled").addListener("change", function(field, value) 
                {
                    var form = this._form.getForm();
        			form.findField('max-entries').setDisabled(!value);
        			form.findField('remaining-message').setDisabled(!value);
        			form.findField('closed-message').setDisabled(!value);
        			form.findField('queue-enabled').setDisabled(!value);
        			
        			var queueEnabled = form.findField('queue-enabled').getValue();
        			form.findField('queue-size').setDisabled(!value || !queueEnabled && value);
                    form.findField('queue-closed-message').setDisabled(!value || !queueEnabled && value);
                    this._box.down('#personalizeQueue').setDisabled(!value || !queueEnabled && value);
                }, this);
			
			this._form.getForm().findField("queue-enabled").addListener("change", function(field, value) 
                {
                    var form = this._form.getForm();
        			form.findField('queue-size').setDisabled(!value);
        			form.findField('queue-closed-message').setDisabled(!value);
        			this._box.down('#personalizeQueue').setDisabled(!value);
                }, this);
			
			this._initialized = true;
		},
		
		/**
		 * Validate limitations
		 * @private
		 */
		_ok: function ()
		{
			var form = this._form.getForm();
			if (!form.isValid())
			{
				return;
			}
			var limitParameters = {}; 
			
			var maxEntriesNb = form.findField('max-entries').getValue();
			if (maxEntriesNb <= 0)
			{
				form.findField('max-entries').markInvalid ("{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_MAX_ERROR}}");
				return;
			}
			var queueSize = form.findField('queue-size').getValue();
			if (queueSize && queueSize <= 0)
			{
				form.findField('queue-size').markInvalid ("{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_MAX_ERROR}}");
				return;
			}
			limitParameters["formId"] = this._formId;
			limitParameters["limit-to-one-entry-by-user"]= form.findField('limit-to-one-entry-by-user').getValue();
			limitParameters["limit-entries-enabled"] = form.findField('limit-entries-enabled').getValue();
			limitParameters["queue-enabled"] = form.findField('queue-enabled').getValue();
			limitParameters["max-entries"] = maxEntriesNb;
			limitParameters["queue-size"] = queueSize;
			limitParameters["remaining-message"] = form.findField('remaining-message').getValue();
			limitParameters["closed-message"] = form.findField('closed-message').getValue();
			limitParameters["queue-closed-message"] = form.findField('queue-closed-message').getValue();
			limitParameters["queue-sender"] = this._queueMsgSender;
			limitParameters["queue-receiver"] = this._queueMsgReceiver;
			limitParameters["queue-subject"] = this._queueMsgSubject || "{{i18n PLUGINS_FORMS_QUEUE_SUBJECT_DEFAULT}}";
			limitParameters["queue-body"] = this._queueMsgBody || "{{i18n PLUGINS_FORMS_QUEUE_BODY_DEFAULT}}";
			
			Ametys.data.ServerComm.callMethod({
                role: "org.ametys.plugins.forms.helper.LimitedEntriesHelper",
                methodName: "setEntriesLimitProperties",
                parameters: [limitParameters],
                callback: {
                    handler: this._setOrRemoveEntriesLimitCb,
                    scope: this
                },
                waitMessage: true,
                errorMessage: true
            });
		},
		
		/**
		 * Callback function after setting entries limit
		 * @param {Object} response the server's response
		 * @private
		 */
		_setOrRemoveEntriesLimitCb: function (response)
		{
			this._box.hide();
			Ext.create('Ametys.message.Message', {
				type: Ametys.message.Message.MODIFIED,
				targets: {
					id: Ametys.message.MessageTarget.FORM_TARGET,
					parameters: {
						id: this._formId
					}
				}
			});
		},
		
		/**
		 * Handler invoked when the box's 'Cancel' button is clicked. Hides the box.
		 * @private
		 */
		_cancel: function ()
		{
			this._box.hide();
		},
		
		/**
         * Open queue message dialog
         * @private
         */
        _openQueueMessageDialog: function()
        {
            var initConfig = {
                initFn: Ext.bind(this._initQueueMsgForm, this),
                title: "{{i18n PLUGINS_FORMS_LIMIT_ENTRIES_QUEUE_MAIL_EDITION}}",
                subject: "{{i18n PLUGINS_FORMS_QUEUE_SUBJECT_DEFAULT}}",
                body: "{{i18n PLUGINS_FORMS_QUEUE_BODY_DEFAULT}}"
            };
            
            var validConfig = {
                validFn: Ext.bind(this._okQueueMsg, this)
            };
            
            Ametys.plugins.forms.helper.FormMailDialogHelper.open(this._formId, initConfig, validConfig, {});
        },
		
		/**
		 * @private
		 * Initialize the form with values provided by the server
		 * @param {Function} cbFunction the callback function
		 */
		_initQueueMsgForm: function (cbFunction)
		{
			var response = {}
			response.sender = this._queueMsgSender;
			response.receiver = this._queueMsgReceiver;
			response.subject = this._queueMsgSubject;
			response.body = this._queueMsgBody;
			
			cbFunction(response);
		},
		
		/**
         * @private
         * Function to call after validating mail informations for the queue
         * @param {String} sender the mail sender
         * @param {String} receiver the mail receiver
         * @param {String} subject the mail subject
         * @param {String} body the mail body
         * @param {Function} cbFunction the callback function
         */
		_okQueueMsg: function(sender, receiver, subject, body, cbFunction)
		{
			this._queueMsgSender = sender;
			this._queueMsgReceiver = receiver;
			this._queueMsgSubject = subject;
			this._queueMsgBody = body;
			
			cbFunction();
		}
	});