/*
 *  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 query and select a server directory.
 * 
 * This widget is a widget registered for fields of type Ametys.form.WidgetManager#TYPE_STRING.<br>
 */
Ext.define('Ametys.plugins.serverdirectory.widgets.ServerDirectory', {
	extend: "Ext.form.field.ComboBox",
	
    /**
     * @cfg {String} [enableDynamicPathsField] The field to enable dynamic paths.
     * If the field value is true, variables will be evaluated but completion will be disabled
     */
    /**
     * @private
     * @property {String} _enableDynamicPathsFieldName The property related to {@link #cfg-enableDynamicPathsField}
     */

	initComponent:function()
	{
		this.callParent(arguments);
		
		this.on('specialkey', this._onSpecialKey, this);
		
		this.on('focus', this._onFocus, this); // load and expand combo when the field is focused
		this.on('select', this._onSelect, this); // load and expand combo when a value is selected
	},
	
	constructor: function(config)
	{
		this._enableDynamicPathsFieldName = config.enableDynamicPathsField || null;

		config = Ext.applyIf(config, {
			allowBlank: false,
			hideTrigger: true,
			triggerAction: 'query',	
			
			minChars: 0,
			width: 490, 
			
			queryDelay: 1000,
			
			valueField: 'value',
			displayField: 'displayText',
			
			store: Ext.create('Ext.data.Store', {
				model: 'Ametys.plugins.serverdirectory.widgets.ServerDirectory.Directory',
				
				proxy: {
					type: 'ametys',
					plugin: 'server-directory',
					url: 'service/server-directory-path.json',
					reader: {
						type: 'json',
						rootProperty: 'items'
					}
				},

				listeners: {
	                beforeload: {fn: this._onStoreBeforeLoad, scope: this}
	            },
				
				sorters: [{property: 'displayText', direction: 'ASC'}]
		    })
		});
		
	    this.callParent(arguments);
	},
	
	/**
	 * @private
	 * Function invoked when the field is focused
	 */
	_onFocus: function()
	{
		this.autocomplete();
		this.onTriggerClick();
	},
	
	getValue: function ()
	{
		var value = this.callParent(arguments);
		if (value && !Ext.String.startsWith(value, 'file:/'))
		{
			value = 'file:/' + value;
		}
		return value;
	},
	
	setValue: function (value)
	{
		this.callParent(arguments);
		
		if (value && !this._initialized)
		{
			this.store.load();
			this._initialized = true;
		}
	},
	
	/**
	 * @private
	 * Function invoked when the field is selected
	 */
	_onSelect: function()
	{
		this.autocomplete();
		this.onTriggerClick();
	},
	
	/**
	 * @private
	 * Function invoked when a key is stroke
	 * @param {Ext.form.field.Base} field the field
	 * @param {Ext.event.Event} e the event
	 */
	_onSpecialKey: function(field, e)
	{
		if (e.getKey() == e.ENTER) 
	    {
			this.autocomplete();
	    }
	},
	
	/**
	 * @private
	 * Determines if dynamic paths is enabled
	 * @return true if dynamic paths is enabled
	 */
	_isDynamicPathsEnabled: function ()
	{
		if (this._enableDynamicPathsFieldName)
		{
			var relativeFields = this.form.getRelativeFields([this._enableDynamicPathsFieldName], this);
			var enableDynamicPathsField = relativeFields[0];
			
			if (enableDynamicPathsField)
			{
				return enableDynamicPathsField.getValue();
			}
		}
		return false;
	},

	/**
	 * Autocomplete store
	 */
	autocomplete: function ()
	{
		if (!this._isDynamicPathsEnabled())
		{
			this.store.load();
		}
	},
	
    /**
     * Set the request parameters before loading the store.
     * @param {Ext.data.Store} store The store.
     * @param {Ext.data.operation.Operation} operation The Ext.data.Operation object that will be passed to the Proxy to load the Store.
     * @private
     */
    _onStoreBeforeLoad: function(store, operation)
	{
		var params = operation.getParams() || {};

		operation.setParams(Ext.apply(params, {
        	query : this.getValue(),
            enableDynamicPaths: this._isDynamicPathsEnabled(),
        }));
	}
});