/*
 *  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 UI helper provides a dialog to select one query on a DataSourcesTree.
 * See {@link #open} method.
 */
Ext.define('Ametys.plugins.externaldata.helper.ChooseQuery', {
    singleton: true,
    
    /**
	 * @property {Ametys.window.DialogBox} _box The dialog box displayed.
	 * @private
	 */
    
    /**
	 * @property {Ametys.plugins.externaldata.DataSourcesTree} _tree The tree in the dialog box.
	 * @private
	 */
    
    /**
 	  * @private
 	  * @property {Boolean} _initialized Indicates if the dialog box is initialized.
 	  */
    
    /**
     * Allows the user to choose a query from the datasource tree.
     * @param {Object} config The configuration options:
     * @param {String} config.icon The full path to icon (16x16) for the dialog box
     * @param {String} config.iconCls The separated CSS classes for dialog box icon
	 * @param {String} config.title The title of the dialog box.
	 * @param {String} config.helpmessage The message displayed at the top of the dialog box.
	 * @param {Function} config.callback The method that will be called when the dialog box is closed. The method signature is <ul><li>id: The id of the query</li><li>title: The query title</li></ul>.
	 * @param {String} [config.siteName] The site name. Can be null to see all sites
	 * @param {String[]} [config.dataSourceType] Filter on data source type ('SQL', 'LDAP'). Can be null.
	 * @param {String} [config.resultType] Filter on result type ('simple' or 'multiple'). Can be null.
     */
    open: function (config)
    {
        this._cb = config.callback;
		
        // Filters
        this._siteName = config.siteName;
        
        var dataSourceTypes = config.dataSourceType || [];
		this._dataSourceTypeFilter = Ext.isArray(dataSourceTypes) ? dataSourceTypes : dataSourceTypes.split(",")
		this._resultTypeFilter = config.resultType;
		
		this._createDialogBox(config.icon, config.iconCls, config.title, config.helpmessage);
	
		this._tree.getStore().load({
			scope: this,
			callback: Ext.bind(function() {
				var rootNode = this._tree.getRootNode();
				
				rootNode.expandChildren(true);
				this._tree.getSelectionModel().select(rootNode);
				this._tree.getView().focusNode(rootNode);
			}, this)
		});
		
		this._box.show();
    },
    
    /**
     * Creates the dialog box if it is not already created
     * @param {String} icon The full path to icon (16x16 pixels) for the dialog box
     * @param {String} iconCls The css class name for the dialog box icon
     * @param {String} title The title of the dialog box.
     * @param {String} helpmessage The message displayed at the top of the dialog box.
     * @private
     */
    _createDialogBox: function (icon, iconCls, title, helpmessage)
    {
    	if (!this._initialized)
    	{
	        this._tree = Ext.create('Ametys.plugins.externaldata.DataSourcesTree', {
	        	flex: 1,
			    scrollable: true,
			    border: false
	        });
	        
	        this._tree.on('beforeload', this._onBeforeLoad, this);
	        this._tree.on('selectionchange', this._onSelectionChange, this);
	        
	        this._box = Ext.create('Ametys.window.DialogBox', {
	            title: title,
	            icon: icon,
	            iconCls: icon ? null : iconCls || 'ametysicon-query-search',
	            
	            bodyPadding: '0',
	            width: 375,
	            height: 490,
	            scrollable: true,
	            
	            layout: {
	                type: 'vbox',
	                align: 'stretch',
	                pack: 'start'
	            },
	            
	            items: [
	        		{
		                xtype: 'component',
		                cls: 'a-text',
		                html: helpmessage,
		                style: {
            				padding: '5px'
       					}
	        		},
		            this._tree
		        ],
	            
	            
	            closeAction: 'hide',
	            buttons : [{
	            		disabled: true,
	            		itemId: 'ok-btn',
	                    text : "{{i18n PLUGINS_EXTERNAL_DATA_HELPER_CHOOSEQUERY_OKBUTTON}}",
	                    handler : Ext.bind(this._ok, this)
	                }, {
	                    text : "{{i18n PLUGINS_EXTERNAL_DATA_HELPER_CHOOSEQUERY_CANCELBUTTON}}",
	                    handler: Ext.bind(function() {
	                    	this._cb(null);
	                    	this._box.hide();
	                    }, this)
	                } 
	            ]
	        });
    	}

		this._initialized = true;
    },
    
    /**
	 * @private
	 * Listener before loading tree store
	 * @param {Ext.data.TreeStore} store The tree store
	 * @param {Ext.data.operation.Operation} operation The object that will be passed to the Proxy to load the Store
	 */
	_onBeforeLoad: function(store, operation)
    {
		var params = {
			siteName: this._siteName,
			dataSourceType: this._dataSourceTypeFilter.length > 0 ? this._dataSourceTypeFilter : null,
			resultType: this._resultTypeFilter
		};
		
		operation.setParams(Ext.apply(operation.getParams() || {}, params ));
    },
    
    /**
     * Listener that is called when a node is selected in the tree.
     * @param {Ext.selection.Model} sm The selection model
     * @param {Ext.data.Model[]} nodes The selected record
     * @private
     */
    _onSelectionChange: function(sm, nodes)
    {
    	var node = nodes[0];
    	// At this point, only a query should be selected.
		var selectedQuery = node != null && node.get('type') == 'query';
		// Enable the 'ok' button if a query node is selected.
		this._box.down('#ok-btn').setDisabled(!selectedQuery);
    },
    
    /**
     * Function called when the user presses the OK button from the dialog box.
     * @private
     */
    _ok: function ()
    {
    	var selection = this._tree.getSelection()[0];
        
        var id = selection.get('id');
		var title = selection.get('name');
		if (this._cb(id, title) !== false)
		{
			this._box.hide();
		}
    }
    
});