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

/**
 * Dialog box used to create or edit a cart.
 * @private
 */
Ext.define('Ametys.plugins.cart.helper.CreateOrEditCart', {
	singleton: true,
	
	/**
	 * @property {Function} _cbFn The callback function to callback after creation
	 * @private
	 */
	
	/**
	 * @property {Object} _params The parameters
	 * @private
	 */
	
	/**
	 * @property {Boolean} _initialized True if the dialog box was already initialized
	 * @private
	 */
	_initialized: false,
	
	/**
	 * Do the job (open the dialog box and so on)
	 * @param {String} mode The mode: "new" to create a new cart, "edit" to edit a cart
	 * @param {Object} params The cart parameters. Can be null for creation.
	 * @param {String} params.id The id of cart to edit. Can not be null if mode is 'edit'.
	 * @param {String} params.title The cart title
	 * @param {String} params.description The cart description
     * @param {String} params.documentation The cart documentation link
	 * @param {Function} callback The callback on successful creation/modification of the cart. The arguments are:
	 * @param {Function} callback.id The cart of the created or modified cart
	 */
	act: function (mode, params, callback)
	{
		this._mode = mode;
		this._cbFn = callback;
		this._params = params || {};

		if (!this._delayedInitialize())
		{
			return false;
		}
		
		this._box.setTitle(mode == 'edit' ? "{{i18n PLUGINS_CART_EDIT_CART_DIALOG_CAPTION}}" : "{{i18n PLUGINS_CART_NEW_CART_DIALOG_CAPTION}}");
		this._box.setIconCls('ametysicon-basket ' + (mode == 'edit' ?  'decorator-ametysicon-edit45' : 'decorator-ametysicon-add64'));
		
		this._box.show();
		this._initForm(params);
	},
	
	/**
	 * @private
	 * Initialize the dialog box.
	 */
	_delayedInitialize: function ()
	{
		if (this._initialized)
		{
			return true;
		}
			
	    this._form = new Ext.FormPanel({
			border :false,
			bodyStyle :'padding:10px 10px 0',
			
			defaults: {
				cls: 'ametys',
				labelAlign: 'top',
				labelSeparator: '',
                width: '100%',
				msgTarget: 'side'
			},
			
			items:[{
			        	xtype: 'textfield',
			        	fieldLabel : "* {{i18n PLUGINS_CART_NEW_CART_DIALOG_TITLE}}",
                        ametysDescription: "{{i18n PLUGINS_CART_NEW_CART_DIALOG_TITLE_DESCRIPTION}}",
			        	name: 'title',
			        	itemId: 'title',
						allowBlank: false		        
			        }, 
			        {
			        	xtype: 'textarea',
			        	fieldLabel :"{{i18n PLUGINS_CART_NEW_CART_DIALOG_DESCRIPTION}}",
                        ametysDescription: "{{i18n PLUGINS_CART_NEW_CART_DIALOG_DESCRIPTION_DESCRIPTION}}",
			        	name :'description',
			        	height: 100
			        },
                    {
                        xtype: 'textfield',
                        fieldLabel :"{{i18n PLUGINS_CART_NEW_CART_DIALOG_DOCUMENTATION}}", 
                        ametysDescription: "{{i18n PLUGINS_CART_NEW_CART_DIALOG_DOCUMENTATION_DESCRIPTION}}",
                        name :'documentation',
                        itemId: 'documentation',
                        warnRegex: new RegExp ('^https?://.*$'),
                        warnRegexText: "{{i18n plugin.core:PLUGINS_CORE_REGEXP_INVALID_HTTP_URL_START}}",
                    }
			 ]
		});
	    	
	    this._box = Ext.create('Ametys.window.DialogBox', {
	    	
	    	title :"{{i18n PLUGINS_CART_NEW_CART_DIALOG_CAPTION}}",
	    	iconCls : "ametysicon-basket decorator-ametysicon-add64",
	    	
	    	layout :'fit',
			width: 430,
				
			items : [ this._form ],
						
			defaultFocus: 'title',
			closeAction: 'hide',
			
			referenceHolder: true,
			defaultButton: 'validate',
			
			buttons: [{
				reference: 'validate',
				text :"{{i18n PLUGINS_CART_NEW_CART_DIALOG_OK}}",
				handler : Ext.bind(this._ok, this)
			}, {
				text :"{{i18n PLUGINS_CART_NEW_CART_DIALOG_CANCEL}}",
				handler : Ext.bind(this._cancel, this)
			}]
		});
	    
	    this._initialized = true;
	    return true;
	},
	
	/**
	 * @private
	 * Initialize the box form
	 * @param {Object} params The cart parameters
	 */
	_initForm: function (params)
	{
		var form = this._form.getForm();
		
		form.findField('title').setValue(params.title || '');
		form.findField('description').setValue(params.description || '');
        form.findField('documentation').setValue(params.documentation || '');
		
		form.findField('title').clearInvalid();
		form.findField('description').clearInvalid();
        form.findField('documentation').clearWarning();
	},
	
	/**
	 * The cancel button handler
	 * @private
	 */
	_cancel: function()
	{
		this._box.close();
	},
	
	/**
	 * Callback on the ok button. 
	 * @private
	 */
	_ok: function()
	{
		var form = this._form.getForm();
		if (!form.isValid())
		{
			return;
		}

		if (this._mode == 'edit')
		{
			var params = [
                this._params.id,
                form.findField('title').getValue(),
                form.findField('description').getValue(),
                form.findField('documentation').getValue()
            ];
			Ametys.plugins.cart.CartsDAO.updateCart(params, this._onCreatedOrUpdated, {scope: this});
		}
		else
		{
			var params = [
                form.findField('title').getValue(),
                form.findField('description').getValue(),
                form.findField('documentation').getValue()
            ];
			Ametys.plugins.cart.CartsDAO.createCart(params, this._onCreatedOrUpdated, {scope: this});
		}
	},
	
	/**
	 * Sends the corresponding message on the bus on successful cart creation/modification
	 * @param {Object} response The server response
	 * @param {Object} params The callback arguments
	 * @private
	 */
	_onCreatedOrUpdated: function(response, params)
	{
		this._box.close();
		
		if (Ext.isFunction(this._cbFn))
		{
			this._cbFn(response.id);
		}
	}
});