/*
 *  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 catalogs.
 * @private
 */
Ext.define('Ametys.plugins.odf.catalog.CatalogActions', {
	singleton: true,
	
	/**
 	 * @private
 	 * @property {String} _mode Can be 'new or 'edit'.
 	 */
 	
 	/**
 	 * @private
 	 * @property {Ametys.window.DialogBox} _box The dialog box for creating/editing a catalog.
 	 */
 	 
 	/**
 	 * @private
 	 * @property {Ext.form.Panel} _formPanel The form panel of the dialog box.
 	 */
 	
 	/**
	 * @private
	 * @property {Boolean} _initialized Indicates if the create/edit dialog box is initialized.
	 */
	
	/**
	 * Creates a new catalog.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	create: function (controller)
	{
 		this._createDelayedInitialize();
 		this._createBox.show();
 		this._initCreateForm();
	},
	
	/**
	 * Edits a new catalog.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	edit: function(controller)
	{
 		var target = controller.getMatchingTargets()[0];
 		this._editDelayedInitialize();
 		this._editBox.show();
 		this._initEditForm(target.getParameters().id);
	},
    
    /**
     * Set a catalog as default catalog
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    setDefault: function(controller)
    {
        var target = controller.getMatchingTargets()[0];
        if (target && !target.getParameters().isDefault)
        {
	        Ametys.odf.catalog.CatalogDAO.setDefaultCatalog([target.getParameters().id]);
        }
    },
	
	/**
	 * Removes a new catalog.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	remove: function(controller)
	{
		var target = controller.getMatchingTargets()[0];
 		
 		Ametys.Msg.confirm("{{i18n PLUGINS_ODF_CATALOG_DELETE_LABEL}}",
 				"{{i18n PLUGINS_ODF_CATALOG_CATALOGACTIONS_DELETE_CONFIRM}}",
 				Ext.bind(this._doRemove, this, [target], 1),
 				this
 		);
	},
 	
 	/**
 	 * Check the user input and actually trigger the removal if necessary
 	 * @param {String} btn The pressed button. Can only be 'yes'/'no'
 	 * @param {Ametys.message.MessageTarget} target The target having as parameter the id of the catalog to delete
 	 * @private
 	 */
 	_doRemove: function(btn, target)
 	{
 		if (btn == 'yes')
	    {
            Ametys.odf.catalog.CatalogDAO.removeCatalog([target.getParameters().id, false, target]);
	    }
 	},
 	
 	/**
	 * @private
	 * Creates the dialog box for catalog creation
	 */
	_createDelayedInitialize: function ()
	{
		if (!this._createInitialized)
		{
			var form = this._createFormPanel();
			
			this._createBox = Ext.create('Ametys.window.DialogBox', {
				title: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_TITLE}}",
	            iconCls: 'odficon-book decorator-ametysicon-add64',
	            
	            width: 500,
		        scrollable: false,
	            
	            items: [{
                    xtype: 'container',
                    name: 'hint',
                    itemId: 'hint',
                    html: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_HINT}}",
                    cls: 'a-text'
                },form],
	            
	            defaultFocus: 'title',
	            closeAction: 'hide',
	            buttons: [{
	                text: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_OK}}",
	                handler: Ext.bind(this._create, this)
	            }, {
	                text: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_CANCEL}}",
	                handler: Ext.bind( function() {this._createBox.close();}, this)
	            }]    
			});
			
			this._createInitialized = true;
		}
		
        return true;
	},
    
    /**
     * @private
     * Creates the dialog box for catalog creation
     */
    _editDelayedInitialize: function ()
    {
        if (!this._editInitialized)
        {
            var form = Ext.create('Ext.form.Panel', {
	            defaultType: 'textfield',
	            defaults: {
	                cls: 'ametys',
	                labelSeparator: '',
	                labelAlign: 'right',
	                labelWidth: 60,
	                width: '90%',
	                msgTarget: 'side'
	            },
	            
	            border: false,
	            scrollable: true,
            
	            items: [
	                {
	                    xtype: 'hidden',
	                    name: 'id'
	                },
	                {
	                    xtype: 'container',
	                    name: 'hint',
	                    itemId: 'hint',
	                    html: "{{i18n PLUGINS_ODF_CATALOG_CATALOGACTIONS_RENAME_HINT}}",
	                    cls: 'a-text'
	                },
	                {
	                    name: 'title',
	                    itemId: 'title',
	                    fieldLabel: "{{i18n PLUGINS_ODF_CATALOG_CATALOGACTIONS_RENAME_CATALOG_NAME}}",
	                    allowBlank: false
	                }
                 ]
            });
            
            this._editBox = Ext.create('Ametys.window.DialogBox', {
                title: "{{i18n PLUGINS_ODF_CATALOG_CATALOGACTIONS_RENAME_TITLE}}",
                iconCls: 'odficon-book decorator-ametysicon-text1',
                
                width: 500,
                scrollable: false,
                
                items: [form],
                
                defaultFocus: 'title',
                closeAction: 'hide',
                buttons: [{
                    text: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_OK}}",
                    handler: Ext.bind(this._edit, this)
                }, {
                    text: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_CANCEL}}",
                    handler: Ext.bind( function() {this._editBox.close();}, this)
                }]    
            });
            
            this._editInitialized = true;
        }
        
        return true;
    },
	
	/**
 	 * Creates the form panel of the create dialog box.
 	 * @return {Ext.form.Panel} The form panel
 	 * @private
 	 */
 	_createFormPanel: function()
 	{
        var fromCatalogFd = Ametys.odf.catalog.CatalogDAO.createComboBox({
            name: 'fromCatalog',
            fieldLabel: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_COPY_CATALOG}}",
            ametysDescription: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_COPY_CATALOG_DESC}}",
            allowBlank: true
        });
        
        var titleFd = Ext.create('Ext.form.field.Text', {
            name: 'title',
            itemId: 'title',
            fieldLabel: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_CATALOG_TITLE}}",
            ametysDescription: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_CATALOG_TITLE_DESC}}",
            allowBlank: false,
            enableKeyEvents: true
        });      
        
		var formPanel = Ext.create('Ext.form.Panel', {
	        defaultType: 'textfield',
	        defaults: {
	        	cls: 'ametys',
	        	labelSeparator: '',
	        	labelAlign: 'right',
                width: '100%',
	        	labelWidth: 150,
	        	msgTarget: 'side'
	        },
            
            bodyStyle: {
               paddingRight: '20px' 
            },
	        
	        border: false,
	        scrollable: true,
	        
	        items: [
		        titleFd,
                Ext.create('Ametys.plugins.odf.catalog.ComputedCode', {
                    fieldLabel: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_CATALOG_CODE}}",
                    ametysDescription: "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_CATALOG_CODE_DESC}}",
                    name: 'code',
                    allowBlank: false,
                    titleField: titleFd
                }),
		        fromCatalogFd
	        ]
        	
 		});
 		
 		return formPanel;
 	},
 	
 	/**
 	 * @private
 	 * Initializes the form for catalog creation
 	 */
	_initCreateForm: function ()
 	{
        this.computeCodeActive = true;
        
 		var form = this._createBox.items.get(1).getForm();
 		
        form.reset();
        form.findField('title').setValue('');
        form.findField('title').focus(false, 100);
        form.findField('code').setValue('');
 	},
    
    /**
     * @private
     * Initializes the form for catalog edition
     * @param {String} id The catalog's id
     */
    _initEditForm: function (id)
    {
        var form = this._editBox.items.get(0).getForm();
        
        form.findField('id').setValue(id);
        Ametys.odf.catalog.CatalogDAO.getCatalog(id, Ext.bind(this._setValues, this));
    },
 	
 	/**
 	 * Fill the form with catalog properties
 	 * @param {Ametys.odf.catalog.Catalog} catalog The catalog.
 	 * @private
 	 */
 	_setValues: function(catalog)
 	{
 		var form = this._editBox.items.get(0).getForm();
 		
	    form.findField('title').setValue(catalog.getTitle());
	    form.findField('title').focus(true, 100);
 	},
 	
 	/**
 	 * @private
 	 * Handler for the 'Ok' button of the dialog box.
     * Create the catalog.
 	 */
    _create: function ()
    {
        var form = this._createBox.items.get(1).getForm();
        if (!form.isValid())
        {
        	return;
        }
        
        var values = form.getValues();
        
        if (values.fromCatalog)
        {
            Ametys.Msg.confirm("{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_COPY_TITLE}}",
                "{{i18n PLUGINS_ODF_CATALOG_ADDCATALOGACTION_COPY_CONFIRM}}",
                function (answer)
                {
                    if (answer == 'yes')
                    {
                        this._createBox.close();
                        Ametys.odf.catalog.CatalogDAO.createCatalog([values.title, values.code, values.fromCatalog]);
                    }
                },
                this
            );
        }
        else
        {
     		Ametys.odf.catalog.CatalogDAO.createCatalog([values.title, values.code, values.fromCatalog], this._validateCb, {scope: this, arguments: {box: this._createBox}} );
        }
    },
    
    /**
     * @private
     * Handler when the 'Ok' button is clicked.
     * Edit the catalog's title
     */
    _edit: function ()
    {
        var form = this._editBox.items.get(0).getForm();
        if (!form.isValid())
        {
            return;
        }
        
        var values = form.getValues();
        Ametys.odf.catalog.CatalogDAO.editCatalog([values.id, values.title], this._validateCb, {scope: this, arguments: {box: this._editBox}} );
    },
    
    /**
     * @private
     * Callback function invoked after created or editing a catalog
     * @param {Object} response The server response
     * @param {Object} args The callback arguments
     */
    _validateCb: function (response, args)
    {
    	if (!response['error'])
    	{
    		args.box.close();
    	}
    }
});

/**
 * @private
 * Field that compute the code
 */
Ext.define('Ametys.plugins.odf.catalog.ComputedCode', {
    extend: 'Ametys.form.AbstractFieldsWrapper',
    
    /**
     * @cfg {Boolean} [computeActive=true] True to active code computing
     */
    computeActive: true,
    
    initComponent: function()
    {
        var me = this;
        this.items = [
              Ext.create('Ext.form.field.Text', {readOnly: true, flex: 1}), 
              Ext.create('Ext.button.Button', {
                width: 20,
		        tooltip: this.computeActive ? "{{i18n PLUGINS_ODF_CATALOG_COMPUTE_CODE_DEACTIVATE}}" : "{{i18n PLUGINS_ODF_CATALOG_COMPUTE_CODE_ACTIVATE}}",
		        iconCls: 'ametysicon-link23',
                pressed: !this.computeActive,
		        enableToggle: true,
		        toggleHandler: Ext.bind(this._activeCodeComputing, this)
              })
        ];
        
        this.callParent();
    },
    
    constructor: function (config)
    {
        this.callParent(arguments);
        
        if (config.titleField)
        {
            config.titleField.on('keyup', this._computeCode, this);
            config.titleField.on('change', this._computeCode, this);
        }
    },
    
    /**
     * @private
     * Activates or deactivates the code computing
     * @param {Ext.Button} btn The button 
     * @param {Boolean} state The next state of the button, true means pressed
     * 
     */
    _activeCodeComputing: function(btn, state)
    {
        this.computeActive = !state;
        
        btn.setIconCls(this.computeActive ? 'ametysicon-link23': 'ametysicon-link55');
        btn.setTooltip(this.computeActive ? "{{i18n PLUGINS_ODF_CATALOG_COMPUTE_CODE_DEACTIVATE}}": "{{i18n PLUGINS_ODF_CATALOG_COMPUTE_CODE_ACTIVATE}}");
    },
    
    /**
     * @private
     * Compute the code
     * @param {Ext.form.Field} field The listen field 
     */
    _computeCode: function(field)
    {
        if (this.computeActive && field.getValue())
        {
            var value = Ext.String.deemphasize(field.getValue().toLowerCase()).trim();
            value = value.replace(/[^\w-]/g, '-').replace(/-+/g, '-');
            this.setValue(value);
        }
    },
    
    setValue: function(value) 
    {
        this.items.get(0).setValue(value);
    },

    getValue: function() 
    {
        return this.items.get(0).getValue();
    }
});