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

/**
 * I18n Input text field for the ribbon
 */
Ext.define('Ametys.plugins.skinfactory.widgets.field.I18nInputTextField', {
	extend : 'Ametys.form.AbstractFieldsWrapper',
	
	alias: ['widget.i18ninputtext'],
	
	initComponent : function() 
	{
		var me = this;
				
	    // The text field
		this.textField = Ext.create('Ext.form.field.Text', {
			hideLabel: true,
			flex: 1,
			checkChangeEvents: ['blur'],
			name: this.name + '-text'
		});
		
		// Language combobox
		this.langCombo = Ext.create('Ext.form.field.ComboBox', {
			forceSelection: true,
	    	editable: false,
	    	triggerAction: 'all',
	    	queryMode: 'local',
	    	
	    	matchFieldWidth: false,
	    	width: 50,
	    	listConfig: {
	    		width: 120
	    	},
	    	
	    	store: this.createStore(),
	    	
	    	valueField: 'name',
	        displayField: 'name',
	    	
	        tpl: Ext.create('Ext.XTemplate',
	        		 '<ul class="x-list-plain">',
	        		 	'<tpl for=".">',
	        		 		'<li role="option" class="x-boundlist-item lang-item">{label} <em>({name})</em></li>',
	        		 	'</tpl>',
	        		 '</ul>'),
	        listeners: {
	        	'change': {fn: this._onSelectLanguage, scope: this, options: { priority: 100 }}
	        }
		});
      
		this.items = [ this.textField, this.langCombo ];			

		this.layout = 'hbox';
		this.cls = this.emptyCls;
		
		this.on("afterrender", this._initializeLanguages, this);
		
		this.callParent(arguments);
	},	
	
	/**
	 * @protected
	 * Returns the store to use for languages
	 */
	createStore: function ()
	{
		return Ext.create('Ext.data.Store', {
			model: 'Ametys.cms.language.Language',
			
	        sorters: [ { property: 'label', direction: "ASC" }]
		})
	},
	
	/**
	 * @private
	 * Listener when the field is rendered. Get the available languages
	 */
	_initializeLanguages: function ()
	{
		Ametys.plugins.skinfactory.SkinParametersManager.getLanguages(Ext.bind(this._getLanguagesCb, this));
	},
	
	/**
	 * @private
	 * Callback after retrieving the list of languages available for the skin.
	 * @param  {Object[]} languages The available languages
	 */
	_getLanguagesCb: function (languages)
	{
		var store = this.langCombo.getStore();
		
		Ext.Object.each(languages, function(name, value) {
			store.add ({
				name: name,
				label: value.label
			});
		});
		
		if (this.value)
		{
			this._initValue(this.value);
		}
	},
	
	/**
	 * @private
	 * Initialize the field values with the given values.
	 * The language store has to be loaded !
	 * @param {Object} values The values
	 */
	_initValue: function (values)
	{
		this.suspendEvent('change');
		
		var store = this.langCombo.getStore();
		var defaultLang = Ametys.plugins.skinfactory.SkinParametersManager.getCurrentLanguage();
		if (defaultLang && store.find('name', defaultLang))
		{
			this.langCombo.setValue(defaultLang);
			this.textField.setValue(values[defaultLang]);
		}
		else
		{
			var firstLang = store.getAt(0).get('name');
			this.langCombo.setValue(firstLang);
			this.textField.setValue(values[firstLang]);
		}
		
		this.resumeEvent('change');
	},
	
	/**
	 * @inheritdoc
     * Sets a data value into the field and updates the display field
     * @param {Object[]} values The values to set.
     */
	setValue: function (values) 
	{	
		if (values && this.langCombo.getStore().getData().length > 0)
		{
			this._initValue(values);
		}
		
		this.callParent([values]);
	},
	
	/**
	 * Set the language value
	 * @param lang The language
	 */
	setLanguage: function (lang)
	{
		var store = this.langCombo.getStore();
		if (this.langCombo.getValue() != lang && store.find('name', lang) != -1)
		{
			this.langCombo.setValue(lang);
		}
	},
	
	getValue: function ()
	{
		var lang = this.langCombo.getValue();
		var text = this.textField.getValue();
		
		if (lang)
		{
			this.value = Ext.clone(this.value);
			this.value[lang] = text;
		}
		
		return this.value;
	},
	
	isEqual: function (value1, value2)
	{   	    
      	if (value1 != null && value2 != null)
      	{
      		for (var i in value1)
      		{
      			if (!value2[i] || value1[i] != value2[i])
      			{
      				return false;
      			}
      		}
      		
      		for (var i in value2)
      		{
      			if (!value1[i] || value1[i] != value2[i])
      			{
      				return false;
      			}
      		}
      		
      		return true;
      	} 
      	else if (value1 == null && value2 == null) 
      	{
      		return true;	
      	} 
      	else 
      	{
      		return false;
      	}   	      	
	}, 	
	
	/**
	 * @private
	 * Listener on the trigger items click. Set the language of the field to the one selected by the trigger.
	 * @param  {Ext.form.field.Field} field The language field
	 */
	_onSelectLanguage: function (field)
	{
		var lang = field.getValue();
		
		if (this.value[lang])
		{
			this.textField.setValue(this.value[lang]);
		}
		else
		{
			this.textField.setValue();
		}
	},
	
	/**
	 * Return the current language of the field.
	 * @return {String} The language code.
	 */
	getCurrentLanguage: function ()
	{
		return this.langCombo.getValue();
	}
});