/*
 *  Copyright 2012 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 helper allows to choose one query from a combo list
 * @private
 */
Ext.define('Ametys.plugins.queriesdirectory.helper.ChooseQuery', {
	singleton: true,
	
	/**
	 * @property {String} The id of the current query.
	 * @private
	 */
	_currentQuery: null,
	
	/**
	 * @property {Boolean} _initialized True if the dialog box was already initialized
	 * @private
	 */
	_initialized: false,

    /**
     * @property {String} [_type] The type of query
     * @private
     */
    
    /**
     * @property {Boolean} [_showConfirm=false] Set to `true` to show a confirmation message on selection.
     * @private
     */
    
    /**
     * @property {String} [_confirmTitle="{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_CONFIRM_TITLE}}"] The title of the confirmation message.
     * @private
     */
    
    /**
     * @property {String} [_confirmText="{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_CONFIRM_TEXT}}"] The text of the confirmation message.
     * @private
     */
    
    /**
     * @property _chooseQueryCallbackFunction The callback function to call after choosing a query
     */
	
    /**
     * @property _createCallbackFunction The callback function to call after creating a new query
     */
	
	/**
	 * Open the dialog box to choose a query in WRITE access
	 * @param {Object} config The configuration options:
	 * @param {String} config.type The type of the query
	 * @param {String} [config.title] The dialog box title
     * @param {String} [config.iconCls] The CSS class for dialog box icon
     * @param {String} [config.icon] The dialog box icon (used only if iconCls is empty)
     * @param {String} [config.value] The query to preselect
	 * @param {String} [config.helpMessage] The dialog box help message
     * @param {String} [config.linkText] The creation link message
     * @param {String} [config.profileAccess='write_access'] The profile access used to retrive the available query 
     * @param {String} [config.showConfirm] true to display confirm message on selection
     * @param {String} [config.chooseQueryCallback] The callback function to be called after query selection
     * @param {String} [config.allowCreation] true to allow the creation of a new query
     * @param {String} [config.createCallback] The callback function to be called after query creation
	 */
	act: function(config)
	{
        this._createCallbackFunction = config.createCallback;

        this._showConfirm = config.showConfirm == true;
        this._confirmTitle = config.confirmTitle || "{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_CONFIRM_TITLE}}";
        this._confirmText = config.confirmText || "{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_CONFIRM_TEXT}}";
        
        this._chooseQueryCallbackFunction = config.chooseQueryCallback;
		this._type = config.type;
		this._params = config.params || {};
        
        this._currentQuery = config.value; 
		
		if (!this._delayedInitialize(config))
		{
			return false;
		}
		this._box.show();
		this._initForm();
	},
	
	/**
     * @private
     * Initialize the dialog box.
     * @param {Object} config The configuration options:
     * @param {String} config.type The type of the query
     * @param {String} [config.title] The dialog box title
     * @param {String} [config.iconCls] The CSS class for dialog box icon
     * @param {String} [config.icon] The dialog box icon (used only if iconCls is empty)
     * @param {String} [config.helpMessage] The dialog box help message
     * @param {String} [config.allowCreation] true to allow the creation of a new query
     * @param {String} [config.linkText] The creation link message
     * @param {String} [config.profileAccess='write_access'] The profile access used to retrive the available query 
     */
	_delayedInitialize: function (config)
	{	
        var type = config.type;
		if (!this._initialized)
		{
			this._box = Ext.create('Ametys.window.DialogBox', {
		    	
		    	title: config.title || "{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_TITLE}}",
		    	iconCls: config.icon ? null : (config.iconCls || 'ametysicon-data110'),
                icon: config.icon,
		    	
		    	cls: 'ametys-dialogbox query',
				width: 430,
				layout: {
					type: 'vbox',
					align: 'stretch'
				},
				
				items : [{
				        	xtype: 'component',
				        	cls: 'a-text',
				        	html: config.helpMessage || "{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_HINT}}"
				        },
				        {
				        	xtype: 'edition.select-query',
				        	fieldLabel : "{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_QUERIES}}",
				        	labelWidth: 60,
				        	labelAlign: 'right',
				        	labelSeparator: '',
				        	name :'query',
				        	itemId: 'query',
				        	
				        	typeAhead: true,
							editable: true,
							forceSelection: true,
							triggerAction: 'all',
                            
                            profile: config.profileAccess || 'write_access',
                            acceptedQueryTypes: [type],
							
				        	width: 390,
				        	allowBlank: false,
				        	
				        	cls: 'ametys'
				        },
				        {
				        	xtype: 'component',
                            cls: 'a-text-warning',
                            itemId: 'no-query',
				        	hidden: true,
				        	html: "{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_NO_QUERY}}"
				        },
				        {
				        	xtype: 'component',
                            cls: 'a-text link',
                            hidden: !config.allowCreation,
				        	html: "<a class='action'>" + (config.linkText || "{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_ADDQUERY}}") + "</a>"
				        }
				],
				
				defaultFocus: 'query',
				closeAction: 'hide',
				
				referenceHolder: true,
				defaultButton: 'validate',
				
				buttons: [{
					reference: 'validate',
					text :"{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_OK}}",
					handler : Ext.bind(this._ok, this)
				}, {
					text :"{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_CANCEL}}",
					handler: function () {this._currentQuery = null; this._box.hide()},
					scope: this
				}]
		    });
		    
		    this._initialized = true;
		}
		else
		{
            if (config.icon)
            {
                this._box.setIcon(config.icon);
            }
            else
            {
                this._box.setIconCls(config.iconCls || 'ametysicon-data110');
            }
            
			this._box.setTitle(config.title || "{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_TITLE}}");
			this._box.items.getAt(0).update(config.helpMessage || "{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_HINT}}");
            this._box.down('#query').setQueryTypes(type);
            this._box.down('#query').setProfileAccess(config.profileAccess || 'write_access');
            this._box.items.getAt(3).update("<a class='action'>" + (config.linkText || "{{i18n PLUGINS_QUERIESDIRECTORY_DIALOG_CHOOSEQUERY_ADDQUERY}}") + "</a>");
            this._box.items.getAt(3).setVisible(config.allowCreation || false);
		}
	    return true;
	},
	
	/**
	 * @private
	 * Function to create a new query
	 */
	_createQuery: function ()
	{
		this._box.hide();
        
        var title = this._type == Ametys.plugins.queriesdirectory.model.QueryFormatting.FORMATTING_TYPE ? "{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_FORMATTING_LABEL}}" : "{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_QUERY_LABEL}}"
		Ametys.plugins.queriesdirectory.helper.CreateOrEditQuery.act({mode: 'new', type: this._type, params: this._params, title: title, callback: this._createCallbackFunction});
	},
    
	/**
	 * @private
	 * Initialize fields
	 */
	_initForm: function ()
	{
		if (!this._clickEventRegistered)
		{
			var action = this._box.items.getAt(3);
			action.mon(action.getEl(), 'click', this._createQuery, this, {delegate: 'a.action'});
			this._clickEventRegistered = true;
		}

        this._box.down('#query').reset();
		this._box.down('#query').getStore().load({callback: this._onLoadQueries, scope: this});
		
	},
	
	/**
	 * Callback function called after queries are loaded
	 * @private
	 */
	_onLoadQueries: function (records, operation, success)
	{
        if (records.length == 0)
        {
            this._box.down('#no-query').setVisible(true);
        }
        else
        {
            this._box.down('#no-query').setVisible(false);
            this._box.down('#query').setValue(this._currentQuery);
        }
	},
	
	/**
	 * The ok button handler. Will call the callback when query is chosen.
	 * @private
	 */
	_ok: function()
	{
		if (!this._box.down('#query').isValid())
		{
			return;
		}

        if (this._showConfirm)
        {
            var body = Ext.String.format(this._confirmText, this._box.down('combo').getDisplayValue());
            
            // Check if the selected query is open in a different tool
    		var toolReplacement = false;
    		var currentTool = this._params.tool
    		if (currentTool)
    	    {
    		    var selectedQueryTool = Ametys.tool.ToolsManager.getTool(currentTool.getFactory().getId() + "$" + this._box.down('#query').getValue());
    		    toolReplacement = currentTool.getParams()["queryId"] != this._box.down('#query').getValue() && selectedQueryTool != undefined;
    	    }
            // If the selected query is open in a different tool, we add a warning to explain that the existing tool will be closed
            if (toolReplacement)
            {
                body += "{{i18n PLUGINS_QUERIESDIRECTORY_SAVE_AS_TOOL_TEXT}}"
            }
    		Ametys.Msg.confirm(this._confirmTitle, 
    		        body, 
                    function(btn) {
                        if(btn == 'yes')
                        {
                            this._chooseQuery();
                        }
                        
                    },
                    this);
        }
        else
        {
            this._chooseQuery();
        }
        
		return;
		
	},
	
	_chooseQuery: function()
	{
        this._currentQuery = null;
        this._box.hide();
        
        if (Ext.isFunction(this._chooseQueryCallbackFunction))
        {
            this._chooseQueryCallbackFunction ({id: this._box.down('combo').getValue(), content: this._params.content});
        }
    }
});