/*
 *  Copyright 2013 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 data source query in current site.<br>
 * See {@link Ametys.plugins.externaldata.helper.ChooseQuery}<br>
 * 
 * This widget is registered for fields of type Ametys.form.WidgetManager#TYPE_STRING.<br>
 * It does NOT handle multiple values.<br>
 * 
 */
Ext.define('Ametys.plugins.externaldata.form.field.SelectDataSourceQuery', {
	extend : 'Ametys.form.AbstractField',
	
	/**
	 * @cfg {String} [resultType] The filter for queries on result type ('SIMPLE' or 'MULTIPLE'). Can be null to not filter on result type.
	 */
	/**
	 * @cfg {String|String[]} [dataSourceType] The filter for queries on data source type ('SQL', 'LDAP'). Can be null to not filter on data source type.
	 */
	/**
	 * @cfg {String} buttonIconCls The CSS class for button icon
	 */
	buttonIconCls: 'ametysicon-data110',
	/**
	 * @cfg {String} buttonTooltipText The button tooltip text
	 */	
	buttonTooltipText : "{{i18n PLUGINS_EXTERNAL_DATA_WIDGET_SELECTQUERY_SELECT_BUTTON_TOOLTIP}}",
	/**
	 * @cfg {String} deleteButtonIconCls The CSS class for the delete button
	 */
	deleteButtonIconCls: 'ametysicon-delete30', 
	/**
	 * @cfg {String} deleteTooltipText The delete button tooltip text
	 */	
	deleteTooltipText : "{{i18n PLUGINS_EXTERNAL_DATA_WIDGET_SELECTQUERY_DELETE_BUTTON_TOOLTIP}}",
	/**
	 * @cfg {String} emptyText The text for empty field
	 */
	emptyText: "{{i18n PLUGINS_EXTERNAL_DATA_WIDGET_SELECTQUERY_NO_QUERY}}",
	
	/**
	 * @cfg {String} dialogBoxIconCls The CSS class for dialog box icon
	 */	
	dialogBoxIconCls: 'ametysicon-data110',
	/**
	 * @cfg {String} dialogBoxTitle The title of dialog box for choosing query
	 */	
	dialogBoxTitle: "{{i18n PLUGINS_EXTERNAL_DATA_WIDGET_SELECTQUERY_DIALOG_TITLE}}",
	
	/**
	 * @cfg {String} dialogBoxHintText The hint text of dialog box for choosing query
	 */	
	dialogBoxHintText: "{{i18n PLUGINS_EXTERNAL_DATA_WIDGET_SELECTQUERY_DIALOG_HINT}}",
	
	/**
	 * @cfg {String} siteName The site name for queries. Default to the current site name.
	 */
	siteName: Ametys.getAppParameter('siteName'),
	
	/**
	 * @inheritdoc
	 * Initializes the longitude/latitude fields, and the showOnMap button
	 */
	initComponent : function() 
	{
		var me = this;
				
	    // Display field.
		this.displayField = Ext.create('Ext.Component', {
			cls: Ametys.form.AbstractField.READABLE_TEXT_CLS,
			html: '',
			flex: 1
		});

		// Button to select the query
		this.selectBtn = Ext.create('Ext.button.Button', {
			iconCls: this.buttonIconCls,
			tooltip: this.buttonTooltipText,
			handler : this._selectQuery,
			scope : this
		});
		
		// Button to delete the query
		this.deleteBtn = Ext.create('Ext.button.Button', {
			iconCls: this.deleteButtonIconCls,          
			tooltip: this.deleteTooltipText,
			handler: this._deleteQuery,
			scope: this,
			hidden: true
		});
      
		this.items = [ this.displayField, this.selectBtn, this.deleteBtn ];			

		this.layout = 'hbox';
		this.cls = this.emptyCls;
		
		this.callParent(arguments);
	},	
	
	/**
	 * @private
	 * Open the dialog box for choosing the query
	 */
	_selectQuery: function ()
	{
		Ametys.plugins.externaldata.helper.ChooseQuery.open({
			iconCls: this.dialogBoxIconCls,
			title: this.dialogBoxTitle,
            helpmessage: this.dialogBoxHintText,
            callback: Ext.bind(this._selectQueryCb, this),
            siteName: this.siteName,
            dataSourceType: this.dataSourceType,
            resultType: this.resultType
		});
	},
	
	setValue: function (value) 
	{	
		this.callParent([value]);
        this._updateUI();
	},
	
	getReadableValue: function ()
    {
        if (this.value)
        {
        	return this._readableValue || this.value;
        }
        else
        {
            return this.emptyText;
        }
    },
	
	getSubmitData: function ()
    {
        var data = {};
        data[this.name] = this.getValue();
        return data;
    },
	
	afterRender: function()
    {
    	this.callParent(arguments);
    	this._updateUI();
    },
	
	/**
	 * Update UI
	 * @private
	*/
	_updateUI: function()
	{	
		var value = this.value;
        
        if (!this.rendered)
        {
            return;
        }
        
        if (value === undefined || Ext.isEmpty(value)) 
        {
            this.deleteBtn.hide();
            this.selectBtn.show();
        }
        else
        {
        	this.deleteBtn.show();
            this.selectBtn.hide();
        }
        
        this._updateDisplayField();
	},	 
	
	/**
	 * Update the display field as a understanding value for the end user
	 * @private
	*/
	_updateDisplayField: function()
	{
		if (!this.rendered)
    	{
    		return;
    	}
		
		if (!Ext.isEmpty(this.value))
		{
			Ametys.cms.externaldata.QueryDAO.getQueryProperties(
	        	[this.value, this.siteName], 
	        	this._getQueryPropertiesCb, 
	        	{scope: this}
	        );
		}
		else
		{
			this.displayField.update(this.getReadableValue());
		}
	},
	
	/**
	 * @private
	 * Callback function invoked after retrieving the query's properties
	 * @param {Object} data The properties
	 */
	_getQueryPropertiesCb: function (data)
	{
		this._readableValue = data.name;
		this.displayField.update(this.getReadableValue());
	},
	
	/**
    * Delete the query value
    * @private
    */
	_deleteQuery: function()
	{
		this.setValue();
        this.clearWarning();
	},
	
	/**
	 * @private
	 * Callback function called after choosing the query.<br>
	 * Update the field value.
	 * @param {String} queryId The id of selected query
	 * @param {String} queryLabel The label of selected query
	*/
	_selectQueryCb: function (queryId, queryLabel)
	{
		if (queryId)
		{
			this.setValue(queryId);
			this._readableValue = queryLabel;
			this.clearWarning();
		}
	}
});