/*
 *  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.
 */
 
 /**
  * UI helper to select automatic newsletters. See #open method.
  */
Ext.define('Ametys.plugins.newsletter.category.AutomaticNewsletterUI', {
	singleton: true,

	/**
	 * @private
	 * @property {Boolean} _initialized true if the dialog box was already initialized
	 */
	/**
 	 * @private
 	 * @property {Ametys.window.DialogBox} _box The dialog box.
 	 */
	
	/**
	 * Open the dialog box
	 * @param {String} categoryId the id of newsletter category
	 * @param {Function} callback the callback function
	 * @param {String} callback.categoryId the id of category
	 * @param {String[]} callback.automaticNewsletterIds the ids of selected automatic newsletters
	 */
	open: function (categoryId, callback)
	{
		this._cbFn = callback;
		
		if (!this._initialized)
		{
			this._getAutomaticNewsletters(categoryId);
		}
		else
		{
			this._initForm (categoryId);
			this._box.show();
		}
	},
	
	/**
	 * @private
	 * Get the existing automatic newsletters
	 * @param {String} categoryId the id of category
	 */
	_getAutomaticNewsletters: function (categoryId)
	{
		Ametys.data.ServerComm.callMethod({
			role: "org.ametys.plugins.newsletter.auto.AutomaticNewsletterDAO",
			methodName: 'getAutomaticNewsletters',
			parameters: [],
			callback: {
				handler: this._getAutomaticNewslettersCb,
				scope: this,
				arguments: {
					categoryId: categoryId
				}
			},
			errorMessage: {
				category: this.self.getName(),
				msg: "{{i18n PLUGINS_NEWSLETTER_AUTOMATIC_DIALOG_NEWSLETTERS_ERROR}}"
			},
			waitMessage: true
		});
	},
	
	/**
	 * Callback function invoked after retrieving the automatic newsletters.
	 * Creates and show the dialog box UI.
	 * @param {Object[]} newsletters the automatic newsletters
	 * @param {Object} args the callbacl arguments
	 */
	_getAutomaticNewslettersCb: function (newsletters, args)
	{
		var items = [{
				xtype: 'hidden',
				name: 'categoryId'
			},
			{
	        	xtype: 'component',
	        	region: 'north',
	            cls: 'text',
	            html: "{{i18n PLUGINS_NEWSLETTER_AUTOMATIC_DIALOG_HELP}}"
	        	
			}
		];
		
		// Create a checkbox for each automatic newsletter
        var boxCfg = {};
		Ext.Array.each (newsletters, function (newsletter, index) {
            var itemId = newsletter.id.replace(/\./g, '-');
			items.push({
				xtype: 'checkboxfield',
	            name: newsletter.id,
	            itemId: itemId,
	            boxLabel: newsletter.label,
	            ametysDescription: newsletter.description,
	            inputValue: true
			});
            if (index == 0)
            {
                boxCfg['defaultFocus'] = itemId;
            }
		});
		
		this._box = Ext.create('Ametys.window.DialogBox', Ext.apply({
			title: "{{i18n PLUGINS_NEWSLETTER_AUTOMATIC_DIALOG_TITLE}}",
	        iconCls: 'ametysicon-envelope14 decorator-ametysicon-gear39',
	        
	        width: 420,
	        scrollable: false,
	        
	        items: {
	        	xtype: 'form',
	        	border: false,
		        defaultType: 'textfield',
		        scrollable: true,
		        defaults: {
		        	labelAlign: 'right',
		        	labelSeparator: '',
		        	width: 350
		        },
		        items: items
	        },
	        
	        closeAction: 'hide',
	        
	        referenceHolder: true,
	        defaultButton: 'validate',
	        
	        buttons: [{
	        	reference: 'validate',
	            text: "{{i18n PLUGINS_NEWSLETTER_AUTOMATIC_DIALOG_OK}}",
	            handler: this._validate,
	            scope: this
	        }, {
	            text: "{{i18n PLUGINS_NEWSLETTER_AUTOMATIC_DIALOG_CANCEL}}",
	            handler: function () {this._box.close()},
	            scope: this
	        }]
		}, boxCfg));
		
		this._initForm (args.categoryId);
		this._box.show();
		
		this._initialized = true;
	},
	
	/**
	 * @private
	 * Initializes the form
	 * @param {String} categoryId The category id.
	 */
	_initForm: function(categoryId)
	{
		var form = this._box.items.get(0).getForm();
		form.reset();
		
		form.findField('categoryId').setValue(categoryId);
		
		Ametys.cms.newsletter.CategoryDAO.getCategory([categoryId], this._getCategoryCb, {scope: this, arguments: {form: form}});
	},
	
	/**
	 * @private
	 * Callback function invoked after getting the category's properties
	 * @param {Ametys.cms.newsletter.NewsletterCategory} category the category
	 * @param {Object} args the callback arguments
	 */
	_getCategoryCb: function (category, args)
	{
		var form = args.form;
		
		var autoIds = category.getAutomaticIds();
		Ext.Array.each (autoIds, function (id) {
			form.findField(id).setValue(true);
		})
	},
	
	/**
	 * Function called when clicking on 'Ok' button
	 * @private
	 */
	_validate: function ()
	{
		var form = this._box.items.get(0).getForm();
		var values = form.getValues();
		
		var categoryId = values.categoryId;
		delete values.categoryId;
		
		var automaticsIds = Ext.Object.getKeys(values);
		this._cbFn (categoryId, automaticsIds);
		this._box.close();
	}
	
});