/*
 *  Copyright 2016 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 color.
 */
Ext.define('Ametys.form.widget.ColorPicker', {
    extend:'Ametys.form.AbstractFieldsWrapper',
    
    /**
     * @cfg {String} buttonText The button text
     */
    buttonText : "{{i18n PLUGINS_CORE_UI_WIDGET_COLORPICKER_SHOW_COLORS_BUTTON_TEXT}}",
    /**
     * @cfg {String} buttonTooltipText The button tooltip text
     */ 
    buttonTooltipText : "{{i18n PLUGINS_CORE_UI_WIDGET_COLORPICKER_SHOW_COLORS_BUTTON_TOOLTIP}}",
    /**
     * @cfg {String} emptyText The text for empty field
     */
    emptyText: "{{i18n PLUGINS_CORE_UI_WIDGET_COLORPICKER_EMPTY_TEXT}}",
    
    /**
     * @cfg {Object/Object[]} listColors An array of color objects, with properties :
     * {String} listColors.label The name of the picker
     * {String[]} [listColors.colors] The list of colors code, such as "FF0000".
     * If listColors is undefined, it will assume the default color configuration.
     */
    
    /**
     * @cfg {Boolean/String} [allowTransparent=false] True to allow selection of a fully transparent color. When used with an enumeration, only colors from the enumeration can be selected so this value is consedered false.
     */
    
    /**
     * @cfg {Boolean/String} [allowOtherColors=true] True to allow selection of custom color. When used with an enumeration, only colors from the enumeration can be selected so this value is consedered false.
     */
    
    initComponent : function() 
    {
        function _getValues(values)
        {
            var a = [];
            
            Ext.Object.eachValue(values, function (value) {
                a.push(value[1]);
            });
            
            return a;
        }
        
        this.value = this.value || "";
        
        var enumValues = this.getInitialConfig('enumeration');
        
        // Color field
        var displayedColorConfig = {
            cls: Ametys.form.AbstractField.READABLE_TEXT_CLS,
            html: '',
            flex: 1
        };
        this._displayedColorField = Ext.create('Ext.Component', displayedColorConfig);

        var listColors = enumValues ? { label: '', colors: _getValues(enumValues) } : eval(this.getInitialConfig('listColors'));
        var colorSelector = Ext.create('Ametys.form.field.ColorSelector', {
            listColors: listColors,
            allowTransparent: enumValues ? false : this.getInitialConfig('allowTransparent'),
            allowOtherColors: enumValues ? false : this.getInitialConfig('allowOtherColors'),
            allowNoColor: this.getInitialConfig('allowBlank'),
            currentColor: this.value,
            callback: Ext.bind(this._onColorSelected, this)
        });
        
        this._colorSelectorMenu = Ext.create('Ext.button.Button', {
            text: this.buttonText,
            tooltip: this.buttonTooltipText,
            menu: {
                items: [colorSelector]
            }
        });
        
        this.items = [ this._displayedColorField, this._colorSelectorMenu ];         

        this.layout = 'hbox';
        
        this.callParent(arguments);
    },
    
    onResize: function(width, height, oldWidth, oldHeight)
    {
        this._displayedColorField.setHeight(height);
    },
    
    setValue: function (value) 
    {   
        this.callParent(arguments);
        this._updateUI();
    },
    
    afterRender: function()
    {
        this.callParent(arguments);
        this._updateUI();
    },
    
    /**
     * Update UI
     * @private
    */
    _updateUI: function()
    {   
        if (!this.rendered)
        {
            return;
        }
        
        this._updateDisplayField();
    },
    
    /**
     * Update the display field as a understanding value for the end user
     * @private
    */
    _updateDisplayField: function()
    {
        if (!this.rendered)
        {
            return;
        }

        var color = this._getColorFromValue(this.value);
        this._displayedColorField.update(color ? "" : this.emptyText);
        this._displayedColorField.setStyle('backgroundColor', color ? '#' + color : '');
    },
    
    /**
     * @private
     * Listener when a color has been selected on the {@link Ametys.form.field.ColorSelector}.
     * Updates the value of the widget.
     * @param {String} color The 6 hexadecimal upper case color code.
     */
    _onColorSelected: function(color)
    {

        value = this._getValueFromColor(color);
        
        this.setValue(value);
        this.clearWarning();
        this._colorSelectorMenu.hideMenu();
    },
    
    /**
     * @private
     * Compute the color from the value
     * @param {String} value A hexadecimal color Or a palete index when enumerated
     * @return {String} The color (hexa code). Can be empty
     */
    _getColorFromValue: function(value)
    {
        var enumValues = this.getInitialConfig('enumeration');
        if (enumValues)
        {
            var finalColor = "";
            Ext.Object.eachValue(enumValues, function(v) {
                if (v[0] == value)
                {
                    finalColor = v[1].substring(1); // Remove heading #
                }
            });
            return finalColor;
        }
        else 
        {
            return value;
        }
    },
    
    /**
     * @private
     * Compute the value from the color
     * @param {String} color A hexadecimal color
     * @return {String} The value (can be the same hexa code, or the index value on enumerated)
     */
    _getValueFromColor: function(color)
    {
        color = color || "";
        
        var enumValues = this.getInitialConfig('enumeration');
        if (enumValues)
        {
            var finalValue = null;
            Ext.Object.eachValue(enumValues, function(value) {
                if (value[1] == color)
                {
                    finalValue = value[0];
                }
            });
            return finalValue;
        }
        else 
        {
            return color;
        }
    }
});