/*
 *  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 surveys, their pages and their questions.
 * @private
 */
Ext.define('Ametys.plugins.survey.SurveyTree', {
 	extend: 'Ext.tree.Panel',
 	
 	/**
 	 * @cfg {Boolean} [surveyOnly=false] Set to true to display only survey (no pages nor questions)
 	 */
	/**
	 * @private
	 * @property {Ext.data.TreeStore} _store The store for this tree.
	 */
 	
 	/**
	 * @private
	 * @property {Ext.Template} _surveyTooltipTpl The template used for survey's tooltip
	 */
    _surveyTooltipTpl : Ext.create('Ext.XTemplate', [ 
                         '<tpl if="description && description != \'\'">',
                            '{description}<br/><br/>',
                         '</tpl>',
                         '<u>{{i18n PLUGINS_SURVEY_TOOL_TOOLTIP_VISIBILITY}}</u> : <span style="white-space: nowrap">{visibility}</span><br/>',
                         '<u>{{i18n PLUGINS_SURVEY_TOOL_TOOLTIP_STATUS}}</u> : <span style="white-space: nowrap">{status}</span><br/>'
                        ]),
                        
 	constructor: function(config)
 	{
 		this._store = Ext.create('Ext.data.TreeStore', {
			model: 'Ametys.plugins.survey.SurveyTree.SurveyNodeEntry',
			
			autoLoad: false,
			proxy: {
				type: 'ametys',
				plugin: 'survey',
				url: 'nodes.json',
				reader: {
					type: 'json'
				},
				extraParams: {
					siteName: Ametys.getAppParameter('siteName'),
					surveyOnly: config.surveyOnly === true
				}
			},
			
			listeners: {
				'beforeload': Ext.bind(this._onBeforeLoad, this)
			}
		});
		
		var root = {
			expanded: false,
			text: '{{i18n PLUGINS_SURVEY_TOOL_ROOT_NODE}}',
			id: 'survey-root-node',
			type: 'root',
			allowDrag: false,
			allowDrop: false
		};
		
		config = Ext.applyIf(config, {
 			cls: 'survey-tree',
 			store: this._store,
 			
 			root: root,
 			rootVisible: true,
 			
 			// Languages combo box
			dockedItems: [{
				dock: 'top',
				xtype: 'toolbar',
				layout: { 
	                type: 'hbox',
	                align: 'stretch'
	            },
				
			    border: false,
				
				defaults : {
					cls: 'ametys',
					labelWidth: 55,
					labelSeparator: ''
				},
				
				items: Ametys.cms.language.LanguageDAO.createComboBox({
					itemId: 'languages-combo',
					fieldLabel: "{{i18n PLUGINS_SURVEY_TOOL_LANGUAGES}}",
					flex: 1,
					listeners: {
			        	'change': Ext.bind(this._onChangeLang, this)
			        }
				})
			}]
 		});
 		
 		this.callParent(arguments);
 		
 		this.on('itemmouseenter', this._createQtip, 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') == 'root')
		{
			return;
		}
		
		Ext.QuickTips.unregister(el);

		var text = node.get('title') || node.get('text');
		
		if (node.get('type') == 'survey')
		{
			text = this._surveyTooltipTpl.applyTemplate ({
				description: node.get('title') || node.get('text'), 
				visibility : node.get('private') ? "{{i18n PLUGINS_SURVEY_TOOL_TOOLTIP_VISIBILITY_PRIVATE}}" : "{{i18n PLUGINS_SURVEY_TOOL_TOOLTIP_VISIBILITY_PUBLIC}}",
	            status: node.get('validated') ? "{{i18n PLUGINS_SURVEY_TOOL_TOOLTIP_STATUS_VALIDATED}}" : "{{i18n PLUGINS_SURVEY_TOOL_TOOLTIP_STATUS_DRAFT}}"
			});
		}
		
		Ext.QuickTips.register({
			target: el,
			id: el.id + '-tooltip',
			title: node.get('text'),
			glyphIcon: node.get('tooltipIconCls'),
			iconDecorator: node.get('tooltipIconDecorator'),
			imageWidth: 48,
			imageHeight: 48,
			text: text,
			inribbon: false
		});
	},
 	
	/**
	 * @private
	 * Listener on selection of the langguage in top combo box
	 */
	_onChangeLang: function ()
	{
		this.getSelectionModel().select(this.getRootNode());
		this.refreshNode();
	},
	
	/**
	 * Listens before loading the tree. 
	 * 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)
	{
		var lang = this.down("combobox[itemId='languages-combo']").getValue();
		
		operation.setParams( Ext.apply(operation.getParams() || {}, {
			nodeType: operation.node.get('type'),
			lang: lang
		}));
	},
 	
 	/**
	 * Refreshes the given node and then expands it.
	 * @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.
	 * @param {Function} [callback] The callback function to call after loading
	 */
	refreshNode: function(node, deep, callback)
	{
		node = node || this.getRootNode();
		deep = deep || false;
		callback = callback || Ext.emptyFn;
		
        this.getStore().load({
            node : node,
            callback : function()
            {
                Ext.defer(this.expandNode, 200, this, [ node, deep, callback ]);
            },
            scope : this
        });
	}
	
 });