/*
 *  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 tags.
 * @private
 */
Ext.define('Ametys.plugins.cms.tag.TagActions', {
    singleton : true,

    /**
     * Function called to add a new tag
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    add: function(controller)
    {
    	var targets = controller.getMatchingTargets();
    	if (targets.length > 0)
        {
    		var parentTagId = targets[0].getParameters().id;
    		if (!this._formPanel)
    		{
	    		this._loadColor(Ext.bind(this._loadTargetTypes, this, [Ext.bind(this._add, this, [parentTagId])]));
    		}
    		else
    		{
    			this._add(parentTagId);
    		}
        }  
    },
    
    /**
	 * Create a tag
	 * @param {String} parentTagId The parent tag id of the created tag
	 * @param {Function} callback The callback
	 * @private
	 */
    _add: function(parentTagId, callback)
    {
    	Ametys.plugins.cms.tag.TagHelper.add(
    			parentTagId,
				this._formPanel,
				Ametys.message.MessageTarget.TAG,
				"org.ametys.cms.tag.jcr.JCRTagsDAO",
				"{{i18n PLUGINS_CMS_HANDLE_TAGS_CREATE}}",
				"ametysicon-tag25 decorator-ametysicon-add64",
				callback
		);
    },
    
    /**
     * Function called to edit a tag
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    edit: function (controller)
    {
    	var targets = controller.getMatchingTargets();
    	if (targets.length > 0)
        {
    		var tagId = targets[0].getParameters().id;
    		if (!this._formPanel)
    		{
	    		this._loadColor(Ext.bind(this._loadTargetTypes, this, [Ext.bind(this._edit, this, [tagId])]));
    		}
    		else
    		{
    			this._edit(tagId);
    		}
        }  
    },
    
    /**
	 * Edit a tag
	 * @param {String} tagId The tag id to edit
	 * @param {Function} callback The callback
	 * @private
	 */
    _edit: function(tagId, callback)
    {
    	Ametys.plugins.cms.tag.TagHelper.edit(
        		tagId,
        		this._formPanel,
        		Ametys.message.MessageTarget.TAG,
        		"org.ametys.cms.tag.jcr.JCRTagsDAO",
        		"{{i18n PLUGINS_CMS_HANDLE_TAGS_EDIT}}",
        		"ametysicon-tag25 decorator-ametysicon-edit45",
        		callback
		);
    },
    
    /**
     * Function called to remove a tag
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    remove: function (controller)
    {
    	var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            var tagId = targets[0].getParameters().id;
            Ametys.plugins.cms.tag.TagHelper.remove(
            		tagId, 
            		Ametys.message.MessageTarget.TAG,
            		"org.ametys.cms.tag.jcr.JCRTagsDAO",
            		"{{i18n PLUGINS_CMS_HANDLE_TAGS_DELETE_TAG_LABEL}}",
            		"{{i18n PLUGINS_CMS_HANDLE_TAGS_DELETE_TAG_CONFIRM}}"
    		);
        }
    },
    
    /**
	 * Get the targets types
	 * @param {Function} callback The callback function
	 * @private
	 */
    _loadTargetTypes: function (callback)
	{
		Ametys.data.ServerComm.callMethod({
			role: "org.ametys.cms.tag.TagsDAO",
			methodName: "getTargetTypes",
			parameters: [],
			callback: {
				scope: this,
				handler: Ext.bind(this._loadTargetsTypesCb, this, [callback], 1),
			},
			errorMessage: true
		});
	},
    
    /**
	 * Load the targets types data into the store
	 * @param {Object[]} targets The list of target object
	 * @param {Function} callback The callback
	 * @private
	 */
	_loadTargetsTypesCb: function (targets, callback)
	{
		var data = [];
		
		// Populate data array with content type informations/
		Ext.Array.forEach(targets, function(target) {
			data.push({
				label: target.label,
				name: target.name
			});
		});
		
		var form = this._formPanel.getForm();
		form.findField('target').getStore().loadData(data);
		
		if (callback) callback();
	},
    
    /**
     * Get the colors
     * @param {Function} callback The callback function
     * @private
     */
    _loadColor: function (callback)
    {
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.cms.tag.TagColorsComponent",
            methodName: "getColors",
            parameters: [],
            callback: {
                scope: this,
                handler: Ext.bind(this._loadColorCb, this, [callback], 1),
            },
            errorMessage: true
        });
    },
    
    /**
     * Load the colors types data into the store
     * @param {Object[]} colors The list of color object
     * @param {Function} callback The callback
     * @private
     */
    _loadColorCb: function (colors, callback)
    {        
        var colorList = [];
        for (var i in colors)
        {
            var color = colors[i];
            var colorObj = [];
            colorObj.push(i);
            colorObj.push(color.main);
            
            colorList.push(colorObj);
        }
        
        var colorField = Ext.create("Ametys.form.widget.ColorPicker", {
            name: 'color',
            fieldLabel: '{{i18n PLUGINS_CMS_HANDLE_TAGS_COLOR}}',
            ametysDescription: "{{i18n PLUGINS_CMS_HANDLE_TAGS_COLOR_DESCRIPTION}}",
            enumeration: colorList
        })
        
        this._initFormPanel(colorField);
        
        if (callback) callback();
    },
    
	/**
	 * Init the form panel
	 * @private
	 */
	_initFormPanel: function(colorField)
    {
    	if (!this._formPanel)
    	{
    		this._formPanel = Ext.create('Ext.form.Panel', {
                border: false,
                defaultType :'textfield',
                
                defaults: {
                    cls: 'ametys',
                    labelWidth: 90,
                    labelAlign: 'right',
                    labelSeparator: '',
                    msgTarget: 'side',
                    width: 340
                },
                
                items: [{
                            xtype: 'hidden',
                            name: 'id'
                        },
                        {
                            xtype: 'hidden',
                            name: 'parentID'
                        },
                        {
                            xtype:'textfield',
                            name: 'title',
                            itemId: 'title',
                            fieldLabel: "{{i18n PLUGINS_CMS_HANDLE_TAGS_TITLE}}",
                            ametysDescription: "{{i18n PLUGINS_CMS_HANDLE_TAGS_TITLE_DESCRIPTION}}",
                            allowBlank: false,
                            enableKeyEvents: true,
                            listeners: {
                                'keyup': Ext.bind(Ametys.plugins.cms.tag.TagHelper.autoFillKey, this)
                            }
                        },
                        {
                            xtype: 'hidden',
                            name: 'name',
                            fieldLabel: "{{i18n PLUGINS_CMS_HANDLE_TAGS_NAME}}",
                            allowBlank: false,
                            regex: /^[A-Za-z0-9_-]+$/,
                            regexText: "{{i18n PLUGINS_CMS_HANDLE_TAGS_INVALID_REGEXP}}"
                        },
                        {
                        	xtype:'textarea',
                        	name: 'description',
                        	fieldLabel: "{{i18n PLUGINS_CMS_HANDLE_TAGS_DESC}}",
                        	ametysDescription: "{{i18n PLUGINS_CMS_HANDLE_TAGS_DESC_DESCRIPTION}}",
                        	height: 70
                        },
                        {
                        	xtype: 'combobox',
                        	name: 'target',
                			fieldLabel: "{{i18n PLUGINS_CMS_HANDLE_TAGS_TARGET_TYPE}}",
                			ametysDescription: "{{i18n PLUGINS_CMS_HANDLE_TAGS_TARGET_TYPE_DESCRIPTION}}",
                			store: Ext.create('Ext.data.Store', {
                				fields: [
                					'name',
                					{name: 'label', type: 'string'}
             					],
             					autoLoad: false,
             					sorters: {property: 'label'}
                			}),
                			queryMode: 'local',
                			displayField: 'label',
            				valueField: 'name',
            				typeAhead: true,
            				editable: true,
            				forceSelection: true,
            				triggerAction: 'all',
            				value: 'CONTENT',
            				allowBlank: false
                        },
                        colorField,
                        {
                        	xtype: 'radiogroup',
                        	name: 'visibility-group',
                        	fieldLabel: "{{i18n PLUGINS_CMS_HANDLE_TAGS_VISIBILITY}}",
                        	items: [
                        			{boxLabel: "{{i18n PLUGINS_CMS_HANDLE_TAGS_VISIBILITY_PUBLIC}}", name: 'visibility', inputValue: 'PUBLIC', checked: true, width: 130},
                        			{boxLabel: "{{i18n PLUGINS_CMS_HANDLE_TAGS_VISIBILITY_PRIVATE}}", name: 'visibility', inputValue: 'PRIVATE', width: 130}
                        			]
                        },
                        {
                            xtype:'checkbox',
                            name: 'priority',
                            fieldLabel: "{{i18n PLUGINS_CMS_HANDLE_TAGS_PRIORITY}}",
                            ametysDescription: "{{i18n PLUGINS_CMS_HANDLE_TAGS_PRIORITY_DESCRIPTION}}"
                        }
                        ]
    		});
    		
    		return false;
    	}
    	
    	return true;
    },

    /**
     * Import tags from a XML file
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    importXml: function (controller)
    {
    	var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
        	var tagId = targets[0].getParameters().id;
        	
        	Ametys.plugins.cms.tag.ImportTagsUI.open (tagId, controller.getInitialConfig('tag-provider'), Ext.bind(this._importCb, this, [targets[0]]));
        }
    },
    
    /**
     * @private 
     * Callback after import success
     * @param {Ametys.message.MessageTarget} target The parent tag target
     */
    _importCb: function (target)
    {
    	Ext.create("Ametys.message.Message", {
    		type: Ametys.message.Message.MODIFIED,
    		parameters: {major: true},
    		targets: target
    	});
    },
    
    /**
     * Create a new tag, whose informations are returned to the callback afterwards. 
     * @param {String} parentId The parent id for tag creation
     * @param {Function} callback The callback function to called after tag creation or edition. Can be null. The arguments are:
     * @param {String} callback.tagId The id of created or edited tag
     * @param {String} callback.tagName The name of created or edited tag
     * @param {String} callback.tagParentId The id of parent tag. Null in edition mode.
     */
    create: function (parentId, callback)
    {
    	var me = Ametys.plugins.cms.tag.TagActions;
    	
    	if (!me._initFormPanel())
		{
    		me._loadTargetTypes(Ext.bind(me._add, me, [parentId, callback]));
		}
    	else
    	{
    		me._add(parentId, callback);
    	}
		
    }
});