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

/**
 * Input text field for the ribbon
 */
Ext.define('Ametys.plugins.skinfactory.widgets.controller.InputText', {
	extend: 'Ametys.ribbon.element.ui.FieldController',
	
	constructor: function (config)
	{
		config['width'] = 260;
		config['width-small'] = 170;
		config['label-width'] = 70;
	
		this.callParent(arguments);
        
        Ametys.message.MessageBus.on(Ametys.message.Message.LOADED, this._onSkinLoaded, this);
	},
	
	createUI: function(size, colspan)
	{
		var element = this.callParent(arguments);
		
		element.labelAlign = "right";
		element.checkChangeEvents = ['change'];
		element.on("change", this._onChange, this);
        element.on("specialkey", this._onSpecialKey, this);
		return element;
	},
    
    /**
     * @private
     * Listener when the skin was loaded. Update the field value.
     * @param {Ametys.plugins.skinfactory.widgets.controller.InputText} field The text input field.
     */
    _onSkinLoaded: function ()
    {
        var value = Ametys.plugins.skinfactory.SkinParametersManager.getParameterValue(this.getInitialConfig("paramId"));
        if (value)
        {
            this.setValue(value);
        }
    },
	
	/**
	 * Listener on the change value event. Save the value of the field.
	 * @param {Ametys.plugins.skinfactory.widgets.controller.InputText} field The field
	 * @param {String} value The text value of the input field.
	 */
	_onChange: function (field, value)
	{
		Ametys.plugins.skinfactory.skin.SkinActions.updateParameter(this.getInitialConfig("paramId"), value);
	},
    
    /**
     * @private
     * Listener on 'specialkey' event. Save the value of the field if press ENTER
     * @param {Ametys.plugins.skinfactory.widgets.controller.InputText} field The field
     * @param {Ext.event.Event} e The event
     */
    _onSpecialKey: function (field, e)
    {
        if (e.getKey() == e.ENTER) 
        {
            var value = field.getValue();
            Ametys.plugins.skinfactory.skin.SkinActions.updateParameter(this.getInitialConfig("paramId"), value);
        }
    }
});