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

/**
 * Create the send mail dialog box.
 */
Ext.define('Ametys.plugins.forms.workflow.SendMailDialog', {
	
	singleton: true,
	
	/**
	 * @private
	 * @property {String} _formId the id of the involved form
	 */
	
	/**
	 * @private
	 * @property {Ametys.ribbon.element.ui.ButtonController} _controller the controller of the clicked menu item
	 */
	
	/**
	 * @private
	 * @property {String} _comment the possible comment
	 */
	
	/**
	 * @private
	 * @property {Function} _callback the callback function to invoke
	 */
	
	/**
	 * @private
	 * @property {Ext.form.Panel} _form the form of the dialog box
	 */
	
	/**
     * @private
     * @property {String} _mailHelperRole the role of the mail helper
     */
	
	/**
	 * Create the dialog box for sending an e-mail with the given parameters
	 * @param {String} formId the id of the form
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller the controller of the button
	 * @param {String} comment the possible comment
	 * @param {String} mailHelperRole the role of the mail helper
     * @param {Function} callback the callback function to use when validating the dialog 
	 */
	create: function(formId, controller, comment, mailHelperRole, callback)
	{
		this._callback = callback;
		this._formId = formId;
		this._controller = controller;
		this._comment = comment;
		this._mailHelperRole = mailHelperRole;
        
		this._initialize();
		this._setValues();
	},
	
	/**
	 * @private
	 * Initialize the dialog box
	 */
	_initialize: function()
	{
		if (this._dialog != null)
		{
			return;
		}
		
		var fieldDoSendCfg = {
			fieldLabel: "{{i18n PLUGINS_FORMS_SEND_MAIL_DIALOG_FIELD_DO_SEND}}",
			name: 'do-send',
			xtype: 'checkboxfield',
			allowBlank: false,
			inputValue: 'on',
			listeners: {'change': Ext.bind(this._onSendMailCheck, this)}
		};
		
		var fieldFromCfg = {
			 fieldLabel: "{{i18n PLUGINS_FORMS_SEND_MAIL_DIALOG_FIELD_FROM_FULLNAME}}",
			 name: 'from-fullname',
			 allowBlank: false,
			 value: "",
			 disabled: true
		};
		
		var store = Ext.create('Ext.data.ArrayStore', {
		    fields: [
		       'id',
		       'text'
		    ],
		    data: [],
		});
		
		var fieldToCfg = {
			 fieldLabel: "{{i18n PLUGINS_FORMS_SEND_MAIL_DIALOG_FIELD_TO}}",
			 name: "to",
			 mode: 'local',
			 forceSelection : true,
			 triggerAction: 'all',		
			 editable: false,
			 valueField: 'id',
	 		 displayField: 'text',
	 		 disabled: true,
	 		 allowBlank: false,
			 xtype: 'combo',
	 		 
			 store: store,
			 value: ""
		};
		
		var fieldSubjectCfg = {
			 fieldLabel: "{{i18n PLUGINS_FORMS_SEND_MAIL_DIALOG_FIELD_SUBJECT}}",
			 name: "subject",
			 itemId: 'subject',
			 allowBlank: false,
			 disabled: true,
			 value: ""
		};
 
 		var fieldBodyCfg = {
 			 xtype: 'textareafield',
 			 fieldLabel: "{{i18n PLUGINS_FORMS_SEND_MAIL_DIALOG_FIELD_BODY}}",
 			 name: "body",
 			 allowBlank: false,
 			 height: 180,
 			 disabled: true,
 			 value: ""
 		};
 		
 		this._form = Ext.create('Ext.form.Panel', {
 			defaults: {
				xtype: 'textfield'
 			},
 			
 			fieldDefaults: {
 				width: 450,
 				labelWidth: 90
 			},
 			border: false,
 			items: [fieldDoSendCfg, fieldFromCfg, fieldToCfg, fieldSubjectCfg, fieldBodyCfg]
 		});
 		
 		this._dialog = Ext.create('Ametys.window.DialogBox', {
 			title: this._controller['dialog-title'] || this._controller.label,
 			iconCls: 'ametysicon-opened29',

 			layout: 'fit',
 			
 			items: [this._form],
 				
 			closeAction: 'hide',

 			defaultFocus: 'subject',
 				
 			referenceHolder: true,
 			defaultButton: 'validate',

 			buttons: [{
		    	reference: 'validate',
				text : "{{i18n PLUGINS_FORMS_SEND_MAIL_DIALOG_OK}}",
				handler: this._ok,
				scope: this
		    }, 
		    {
				text : "{{i18n PLUGINS_FORMS_SEND_MAIL_DIALOG_CANCEL}}",
				handler: function() {this._dialog.hide()},
				scope: this
		    }]
 		});
	},
	
	/**
	 * @private
	 * Listener function invoked whenever the "Send" checkbox value changes
	 * @param {Ext.form.field.Checkbox} checkbox the checkbox
	 * @param {Object} newValue the new value of the checkbox
	 */
	_onSendMailCheck: function (checkbox, newValue)
	{
		var form = this._form.getForm();
	
		form.findField('to').setDisabled(!newValue);
		form.findField('subject').setDisabled(!newValue);
		form.findField('body').setDisabled(!newValue);
	},
	
	/**
	 * @private
	 * Retrieve and set the values from the server
	 */
	_setValues: function()
	{
		var entryId = this._controller.entries[0];
		var formId = this._formId;
		
		Ametys.data.ServerComm.callMethod({
			role: this._mailHelperRole,
			methodName: "getMailInfo",
			parameters: [formId, entryId],
			callback: {
				scope: this,
				handler: this._setValuesCb
			},
			errorMessage: "{{i18n PLUGINS_FORMS_MAIL_INFORMATION_ERROR}}"
		});
	},
	
	/**
	 * @private
	 * Callback for the information retrieval process
	 * @param {Object} response the server's response
	 * @param {Object} args the callback arguments
	 */
	_setValuesCb: function(response, args)
	{
		var sendMailInfo = response['send-mail'];
	
		var currentUser = sendMailInfo['current-user'];
		var currentUserFullName = currentUser.fullname;
		
		var senderStandardizedName = currentUserFullName + " <" + currentUser.email + ">";
		
		var emails = sendMailInfo.emails;
	
		var emailsInfo = [];
		Ext.each(emails, function(email) {
			emailsInfo.push([email.value, email.displayValue]);
		});
		
		if (Ext.isEmpty(emailsInfo))
		{
			// Use either the configured title or the name of the workflow action for the dialog title
			Ametys.Msg.confirm(
					this._controller['dialog-title'] || this._controller.label,
					"{{i18n PLUGINS_FORMS_SEND_MAIL_DIALOG_NO_MAIL_TEXT}}", 
					function (answer) {
						if (answer == 'yes')
						{
							this._callback(
								this._formId,
								this._controller,
								this._comment,
								{}
							);
						}
					}, 
					this
			);
		}
		else
		{
			var form = this._form.getForm();
			
			form.findField('from-fullname').setValue(senderStandardizedName);
			
			var fieldTo = form.findField('to'); 
			
			fieldTo.getStore().removeAll();
			fieldTo.getStore().loadData(emailsInfo);
			fieldTo.setValue(emailsInfo[0][0]);
			
			var subjectKey = this._controller['subject-key'];
			var bodyKey = this._controller['body-key'];
			bodyKey = bodyKey == "" ? "" : bodyKey + "\n\n" + currentUserFullName;
			bodyKey = bodyKey.replace(/<br\s*\/?>/g, '\n');
			
			form.findField('subject').setValue(subjectKey);
			form.findField('body').setValue(bodyKey);
			
			this._dialog.show();
			
			form.findField('do-send').setValue(true);
		}
	},
	
	/**
	 * @private
	 * Function invoked when the 'Ok' button is clicked or when the 'Enter' key is pressed
	 */
	_ok: function()
	{
		var form = this._form.getForm();
		if (form.isValid())																									
		{
			var values = {};
	
			var sendMail = form.findField('do-send').getValue();
			if (sendMail)
			{
				values["recipient"] = form.findField('to').getValue();
				values["subject"] = form.findField('subject').getValue();
				values["body"] = form.findField('body').getValue();
			}
			
			this._dialog.hide();
			
			this._callback(this._formId, this._controller, this._comment, Ext.JSON.encode(values));
		}
	},
	
	/**
	 * @private
	 * Function invoked when the 'Cancel' button is clicked 
	 */
	_cancel: function()
	{
		this._dialog.hide();
	}
});