/*
 *  Copyright 2015 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.
 */
 
/**
 * Singleton class to handle actions on newsletter categories.
 * @private
 */
 Ext.define('Ametys.plugins.newsletter.category.CategoryActions', {
 	singleton: true,
 	
 	/**
 	 * @private
 	 * @property {String} _mode Can be 'new or 'edit'.
 	 */
 	
 	/**
 	 * @private
 	 * @property {Ametys.window.DialogBox} _dialog The dialog box for creating/editing a category.
 	 */
 	 
 	/**
 	 * @private
 	 * @property {Ext.form.Basic} _form The form of the dialog box.
 	 */
 	
 	/**
	 * @private
	 * @property {Boolean} _initialized Indicates if the create/edit dialog box is initialized.
	 */
 	
 	/**
 	 * Creates a new newsletter category.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	addCategory: function(controller)
 	{
 		this._mode = 'new';
 		var target = controller.getMatchingTargets()[0];
 		this._doEdit(target);
 	},
 	
 	/**
 	 * Edits a given newsletter category.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	editCategory: function(controller)
 	{
 		this._mode = 'edit';
 		var target = controller.getMatchingTargets()[0];
 		this._doEdit(target);
 	},
 	
 	/**
 	 * Deletes a given newsletter category.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	deleteCategory: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		
 		Ametys.Msg.confirm("{{i18n PLUGINS_NEWSLETTER_HANDLE_CATEGORY_DELETE}}",
 				"{{i18n PLUGINS_NEWSLETTER_HANDLE_CATEGORY_DELETE_CONFIRM}}",
 				Ext.bind(this._doDelete, this, [target], 1),
 				this
 		);
 	},
 	
 	/**
 	 * Affects the selected template to the selected newsletter category.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	setTemplate: function(controller)
 	{
 		var categoryId = '';
 		var currentSelection = Ametys.message.MessageBus.getCurrentSelectionMessage().getTarget();
 		if (currentSelection && currentSelection.getId() == "newsletter-category")
 		{
 			categoryId = currentSelection.getParameters().id;
 		}
 		
 		Ametys.cms.newsletter.CategoryDAO.applyTemplates([[categoryId], controller.name]);
 	},
 	
 	/**
 	 * Displays a dialog box to allow the user to create/edit a newsletter category.
 	 * @param {Ametys.message.MessageTarget} target The target (a newsletter category) to edit or the parent target (a category provider) where to create
 	 * @private
 	 */
 	_doEdit: function(target)
 	{
 		if (!this._delayedInitialize()) 
 		{
 			return;
 		}
 		
 		if (this._mode == 'new')
 		{
 			this._dialog.setTitle("{{i18n PLUGINS_NEWSLETTER_HANDLE_CATEGORY_CREATE}}");
 			this._dialog.setIconCls('ametysicon-catalog2 decorator-ametysicon-add64');
 		}
 		else
 		{
 			this._dialog.setTitle("{{i18n PLUGINS_NEWSLETTER_HANDLE_CATEGORY_EDIT}}");
 			this._dialog.setIconCls('ametysicon-catalog2 decorator-ametysicon-edit45');
 		}
 		
 		this._dialog.show();
 		this._initForm(target);
 	},
 	
 	/**
 	 * The action to perform when the user clicks on a button from the deleting message box.
 	 * @param {String} btn The pressed button. Can only be 'yes'/'no'
 	 * @param {Ametys.message.MessageTarget} target The message target of the category to delete
 	 * @private
 	 */
 	_doDelete: function(btn, target)
 	{
 		var categoryId = target.getParameters().id;
 		if (btn == 'yes')
	    {
	        Ametys.cms.newsletter.CategoryDAO.deleteCategory([categoryId, target]);
	    }
 	},
 	
 	/**
     * Initializes the dialog box to create or edit a category. 
     * @return {Boolean} True on success.
     * @private
     */
 	_delayedInitialize: function()
 	{
 		if (this._initialized)
 		{
 			return true;
 		}
 		
 		 //Create the form
 		var formPanel = Ext.create('Ext.form.Panel', {
 			labelWidth: 80,
 			border: false,
 			defaults: {
 				cls: 'ametys',
 				labelSeparator: '',
 				width: '100%',
 				labelAlign: 'right',
 				msgTarget: 'side'
 			},
 			
 			scrollable: true,
 			items: [
 				{
 					xtype: 'hidden',
 					name: 'id'
 				},
 				{
 					xtype: 'hidden',
 					name: 'parentId'
 				},
 				{
 					xtype: 'hidden',
 					name: 'lang'
 				},
 				{
 					xtype: 'textfield',
 					itemId: 'title',
 					name: 'title',
 					fieldLabel :"{{i18n PLUGINS_NEWSLETTER_HANDLE_CATEGORY_TITLE}}",
 					allowBlank: false,
 					width: 350
 				},
 				{
 					xtype: 'textarea',
 					name: 'description',
 					fieldLabel: "{{i18n PLUGINS_NEWSLETTER_HANDLE_CATEGORY_DESC}}",
 					width: 350,
 					height: 70
 				}
 			]
 			
 		});
 		
 		this._form = formPanel.getForm();
 		
 		// Create the dialog box
 		this._dialog = Ext.create('Ametys.window.DialogBox', {
 			title: "{{i18n PLUGINS_NEWSLETTER_HANDLE_CATEGORY_CREATE}}",
 			iconCls: 'ametysicon-catalog2 decorator-ametysicon-add64',
 			
 			layout: 'fit',
 			width: 400,
 			
 			items: [formPanel],
 			
 			defaultFocus: 'title',
 			closeAction: 'hide',
 			
 			referenceHolder: true,
 			defaultButton: 'validate',
 			
 			buttons: [{
 				reference: 'validate',
 				text: "{{i18n PLUGINS_NEWSLETTER_HANDLE_DIALOG_BUTTON_OK}}",
 				handler: Ext.bind(this._ok, this)
 			}, {
 				text: "{{i18n PLUGINS_NEWSLETTER_HANDLE_DIALOG_BUTTON_CANCEL}}",
 				handler: Ext.bind(this._cancel, this)
 			}]
 		});
 		
 		this._initialized = true;
 		
 		return true;
 	},
 	
 	/**
 	 * The action to perform when the user clicks on the OK button from the creating/editing dialog box.
 	 * @param {Ext.button.Button} button The clicked button.
 	 * @param {Ext.event.Event} event The click event.
 	 * @private
 	 */
 	_ok: function(button, event)
 	{
 		if (!this._form.isValid())
 		{
 			return;
 		}
 		
 		var params = this._form.getValues();
 		params.siteName = Ametys.getAppParameter('siteName');
 		if (this._mode == 'new')
 		{
 			Ametys.cms.newsletter.CategoryDAO.createCategory(
 					[params.parentId, params.title, params.description, params.siteName, params.lang], 
 					this._createOrEditCategoryCb,
 					{scope: this}
 			);
 		}
 		else
 		{
 			params.id = this._form.findField('id').getValue();
 			Ametys.cms.newsletter.CategoryDAO.editCategory(
 					[params.id, params.title, params.description],
 					this._createOrEditCategoryCb,
 					{scope: this}
 			);
 		}
 	},
 	
 	/**
 	 * The action to perform when the user clicks on the cancel button from the creating/editing dialog box.
 	 * @param {Ext.button.Button} button The clicked button.
 	 * @param {Ext.event.Event} event The click event.
 	 * @private
 	 */
 	_cancel: function(button, event)
 	{
		this._dialog.hide();
 	},
 	
 	/**
 	 * Initializes the form.
 	 * @param {Ametys.message.MessageTarget} target The target (a newsletter category) to edit or the parent target (a category provider) where to create
 	 * @private
 	 */
 	_initForm: function(target)
 	{
		var lang = target.getParameters().lang;
		
 		if (this._mode == 'new')
 		{
 			// Fill the form
	 		this._form.findField('id').setValue('');
	 		this._form.findField('parentId').setValue(target.getParameters().id || '');
	 		this._form.findField('lang').setValue(lang);
	 		this._form.findField('title').setValue('{{i18n PLUGINS_NEWSLETTER_HANDLE_CATEGORY_DEFAULT_TITLE}}');
	 		this._form.findField('description').setValue('');
 		}
 		else // this._mode == 'edit'
 		{
 			var id = target.getParameters().id;
 			Ametys.cms.newsletter.CategoryDAO.getCategory([id], this._setValues, {scope: this});
 		}
 	},
 	
 	/**
 	 * Fill the create/edit form with some values.
 	 * @param {Ametys.cms.newsletter.NewsletterCategory} category The newsletter category
 	 * @private
 	 */
 	_setValues: function(category)
 	{
 		this._form.findField('id').setValue(category.getId());
 		this._form.findField('parentId').setValue(category.getParentId() || '');
 		this._form.findField('lang').setValue(category.getLang());
 		this._form.findField('title').setValue(category.getTitle());
 		this._form.findField('description').setValue(category.getDescription());
 	},
 	
 	/**
 	 * Callback function after the server succeeded in creating/editing a newsletter category.
 	 * Hides the dialog box.
 	 * @param {Object} response The response provided by the server.
 	 * @private
 	 */
 	_createOrEditCategoryCb: function(response)
 	{
 		if (response['message'] == null)
 		{
 			this._dialog.hide();
 		}
 	}
 	
});