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

/**
 * This class provides a widget to select a newsletter category.<br>
 * This widget does not handle multiple values.
 * This widget is registered for fields of type Ametys.form.WidgetManager#TYPE_STRING.
 */
Ext.define('Ametys.cms.newsletter.widget.SelectCategory', {
    extend : 'Ametys.form.AbstractField',
    
    xtype: 'edition.select-newsletter-category',
    
    /**
     * @cfg {String} buttonIcon The full path to the button icon (in 16x16 pixels)
     */
    buttonIcon: null,
    /**
     * @cfg {String} buttonIconCls The CSS class to apply to the select button 
     */
    buttonIconCls: 'ametysicon-catalog2',
    
    /**
     * @cfg {String} buttonTooltipText The button tooltip text
     */ 
    buttonTooltipText : "{{i18n PLUGINS_NEWSLETTER_WIDGET_SELECT_CATEGORY}}",
    /**
     * @cfg {String} deleteButtonIcon The full path to the delete button icon (in 16x16 pixels)
     */
    deleteButtonIcon: null,
    /**
     * @cfg {String} [deleteButtonIconCls=ametysicon-delete30] The separated CSS classes to apply to delete button
     */
    deleteButtonIconCls: 'ametysicon-delete30', 
    /**
     * @cfg {String} deleteTooltipText The delete button tooltip text
     */ 
    deleteTooltipText : "{{i18n PLUGINS_NEWSLETTER_WIDGET_DELETE_CATEGORY}}",
    /**
     * @cfg {String} emptyText The text for empty field
     */
    emptyText: "{{i18n PLUGINS_NEWSLETTER_WIDGET_SELECT_CATEGORY}}",
    /**
     * @cfg {Boolean} multiple True to allow multi-selection and display checkboxes (defaults to false).
     */
    multiple: false,
    
    constructor: function (config)
    {
        config.multiple = config.multiple === true || config.multiple === 'true';
    	this.callParent(arguments);
    },
    
    initComponent : function() 
    {
        var me = this;
                
        var displayConfig = Ext.applyIf(this.displayConfig || {}, {
        	cls: Ametys.form.AbstractField.READABLE_TEXT_CLS,
            html: '',
            flex: 1
        });
        this.displayField = Ext.create('Ext.Component', displayConfig);

        // Button to open the dialog box for choosing category
        var btnConfig = Ext.applyIf(this.btnConfig || {}, {           
            icon: this.buttonIcon,
            iconCls: this.buttonIcon ? null : this.buttonIconCls,
            tooltip: this.buttonTooltipText,
            handler : this._chooseCategory,
            scope : this
        });
        this._selectCategoryBtn = Ext.create('Ext.button.Button', btnConfig);
        
        // Button which deletes the value.
        var deletBtnConfig = Ext.applyIf(this.deletBtnConfig || {}, {
            icon: this.deleteButtonIcon,    
            iconCls: this.deleteButtonIconCls,          
            tooltip: this.deleteTooltipText,
            handler: this._deleteValue,
            scope: this,
            hidden: true
        });
        this._deleteBtn = Ext.create('Ext.button.Button', deletBtnConfig);
      
        this.items = [ this.displayField, this._selectCategoryBtn, this._deleteBtn ];

        this.layout = 'hbox';
        this.cls = [Ametys.form.AbstractField.BASE_FIELD_CLS, this.emptyCls];
        
        this.callParent(arguments);
    }, 
    
    /**
     * Delete the current widget value
     * @private
     */
	_deleteValue: function()
	{
		this.setValue('');
		this._updateUI();
	},
    
    afterRender: function()
    {
        this.callParent(arguments);
        this._updateUI();
    },
    
    /**
     * Update UI
     * @private
     */
    _updateUI: function()
    {   
        var value = this.value;
        
        if (!this.rendered)
        {
            return;
        }
        
        if (value === null || value === undefined || value === "" || this.value.length === 0) 
        {
            this._deleteBtn.hide();
            this._selectCategoryBtn.show();
        }
        else
        {
            if (!this.multiple)
            {
                this._deleteBtn.show();
	            this._selectCategoryBtn.hide();
            }
        }
        
        this._updateDisplayField();
    },    

    /**
     * Update the display field as a understanding value for the end user
     * @private
     */
    _updateDisplayField: function()
    {
        if (!this.rendered)
        {
            return;
        }
        
        if (this.value)
        {
            Ametys.cms.newsletter.CategoryDAO.getCategories([Ext.Array.from(this.value)], this._updateDisplayFieldCb, {scope: this});
        }
        else
        {
            this._updateDisplayFieldCb(null);
        }
    },

    /**
     * Transform the widget value in a human readable string
     * @return {String} a human readable string
     */
    getReadableValue: function ()
    {
        if (this.value !== null && this.value !== undefined && this.value !== "" && this.value.length > 0)
        {
            var result = this._readableValue || this.value;
            return result;
        }
        else
        {
            return this.emptyText;
        }
    },
    
    /**
     * @inheritdoc
     * Sets a data value into the field and updates the display field
     * @param {Object} value The value to set.
     */
    setValue: function (value) 
    {   
        this.callParent([value]);
        this._updateUI();
    },
    
    getSubmitData: function ()
    {
        var data = {};
        data[this.name] = this.getValue();
        return data;
    },
    
    /**
     * @private
     * Open the dialog box for choosing a category
     */
    _chooseCategory: function()
    {
    	var value = this.getValue() || '';
    	
    	var langContext;

    	langContext = this._getCurrentLangName();
        
    	var config = {
            value: value,
            langContext: langContext,
            callback:  Ext.bind(this._chooseCategoryCb, this),
            multiple: this.multiple
        };
            
        Ametys.cms.newsletter.helper.ChooseCategory.open(config);
    },
    
    /**
     * Get the current language
     * @return the current language
     * @private
     */
    _getCurrentLangName: function ()
    {
    	// First search in current selection
    	var pageTarget = Ametys.message.MessageBus.getCurrentSelectionMessage().getTarget(Ametys.message.MessageTarget.PAGE);
    	if (pageTarget != null)
    	{
    		return pageTarget.getParameters().lang;
    	}
    	
    	return Ametys.cms.language.LanguageDAO.getCurrentLanguage();
    },
    
    /**
     * Callback function called after selecting a category.
     * Update the field value.
     * @param {String} category The id of the selected category
     * @private
    */
    _chooseCategoryCb: function (category)
    {
        this.setValue(category);
    },
    
    /**
     * Set the readable value from a category
     * @param {Ametys.cms.newsletter.NewsletterCategory} category the newsletter category
     * @private
     */
    _updateDisplayFieldCb: function (category)
    {
        if (category)
        {
            this._readableValue = category.map(function(elem){
                return elem.getTitle();
            }).join(", ");
        }
        
        this.displayField.update(this.getReadableValue());
    },
    
});