/*
 *  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 Tree for data sources.
 * @private
 */
 Ext.define('Ametys.plugins.externaldata.DataSourcesTree', {
 	extend: 'Ext.tree.Panel',
 	
 	/**
	 * @private
	 * @property {Ext.Template} _tooltipTpl The template used for nodes' tooltip
	 */
    _tooltipTpl : Ext.create('Ext.XTemplate', [ 
                         '<tpl if="description && description != \'\'">',
                            '{description}<br/>',
                         '</tpl>',
                         '<tpl if="resultType && resultType != \'\'">',
                         	'<tpl if="description && description != \'\'">',
                         		'<br/>',
                         	'</tpl>',
                            '<u>{{i18n PLUGINS_EXTERNAL_DATA_UI_HELPER_QUERY_RESULTTYPE}}</u> : <span style="white-space: nowrap">{resultType}</span><br/>',
                         '</tpl>'
                        ]),
                        
 	constructor: function(config)
 	{
 		var store = Ext.create('Ext.data.TreeStore', {
			model: 'Ametys.plugins.externaldata.DataSourcesTree.DataSourceEntry',
			autoLoad: false,
			
			proxy: {
				type: 'ametys',
				plugin: 'external-data',
				url: 'nodes.json',
				reader: {
					type: 'json'
				},
				extraParams: {
					siteName: Ametys.getAppParameter('siteName')
				}
			},
			
			sorters: [
				{
					property: 'text',
					direction: 'ASC'
				}
			]
		});
		store.on('beforeload', this._onBeforeLoad, this);
		
		var root = {
			expanded: false,
			text: '{{i18n PLUGINS_EXTERNAL_DATA_ROOT_DATASOURCES}}',
			id: 'root',
			type: 'root',
			allowDrag: false,
			allowDrop: false
		};
			
 		Ext.apply(config, {
 			store: store,
 			
 			root: root,
 			rootVisible: true
 		});
 		
 		this.callParent(arguments);
 		
 		this.on('itemmouseenter', this._createQtip, this);
 	},
 	
 	/**
	 * Listens before loading node. 
	 * The load action will be canceled if it returns false 
	 * @param {Ext.data.Store} store The store.
	 * @param {Ext.data.operation.Operation} operation The Ext.data.operation.Operation object that will be passed to the Proxy to load the Store.
	 * @param {Object} eOpts The options object passed to Ext.util.Observable.addListener.
	 * @return {Boolean} False if the load action will be canceled.
	 * @private
	 */
	_onBeforeLoad: function(store, operation, eOpts)
	{
		operation.setParams( Ext.apply(operation.getParams() || {}, {
			nodeType: operation.node.get('type')
		}));
	},
 	
 	/**
	 * Refreshes the given node
	 * @param {Ext.data.NodeInterface} [node] The node to refresh. Root node by default.
	 * @param {Boolean} [deep] True to expand nodes all the way down the tree hierarchy.
	 */
	refreshNode: function(node, deep)
	{
		node = node || this.getRootNode();
		deep = deep || false;
		
        this.getStore().load({
            node : node,
            callback : function()
            {
                Ext.defer(this.expandNode, 200, this, [ node, deep, null ]);
            },
            scope : this
        });
	},
	
	 /**
     * @private
     * Destroy and create the node tooltip when the mouse enters the node
     * @param {Ext.view.View} view The tree view
     * @param {Ext.data.Model} node The tree node
     * @param {HTMLElement} el The node's element
     */
    _createQtip: function (view, node, el)
    {
    	if (node.get('type') == 'datasource' || node.get('type') == 'query')
    	{
    		Ext.QuickTips.unregister(el);
    		Ext.QuickTips.register(Ext.apply({target: el, id: el.id + '-tooltip'}, this._getTooltip(node)));
    	}
	},
	
	/**
	 * Get the tooltip configuration
	 * @param {Ext.data.Model} node The tree node
	 * @returns {Object} The tooltip configuration. See Ametys.ui.fluent.Tooltip.
	 * @private
	 */
	_getTooltip: function(node)
	{
		var text = this._tooltipTpl.applyTemplate ({
			description: Ametys.convertTextareaToHtml(node.get('description')), 
			resultType : this._convertResultType(node.get('resultType'))
		});
		
		return {
			title: node.get('name'),
			text: text,
			glyphIcon: node.get('tooltipGlyphIcon'),
			iconDecorator: node.get('tooltipIconDecorator'),
			imageWidth: 48,
			imageHeight: 48,
			inribbon: false
		};
	},
	
	/**
	 * @private
	 * Convert the result type raw value in readable value
	 * @param resultType The result type
	 * @returns The readable result type
	 */
	_convertResultType: function (resultType)
	{
		if (Ext.isEmpty(resultType))
		{
			return null;
		}
		
		return resultType == 'SIMPLE' ? "{{i18n PLUGINS_EXTERNAL_DATA_UI_HELPER_QUERY_RESULTTYPE_SIMPLE}}" : "{{i18n PLUGINS_EXTERNAL_DATA_UI_HELPER_QUERY_RESULTTYPE_MULTIPLE}}";
	}
	
 });