/*
 *  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 tool displays the cache statistics of the back
 */

Ext.define('Ametys.plugins.web.administration.CacheStatisticsBackTool', {
	extend: 'Ametys.tool.Tool',
	
	/**
	 * @private
	 * @property {Ext.tree.Panel} _tree The tree panel
	 */
	
	/**
	 * @private
	 * @property {String} _siteName The selected site
	 */
	
	/**
	 * @private
	 * @property {String[]} _contexts the contexts' list
	 */
	constructor: function()
	{
		this.callParent(arguments);
		
		// Activate all contexts
		Ametys.plugins.web.administration.CacheStatisticsBackContext.activateContexts(["back-default", "preview-default", "preview-live", "front-live"]);
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
	},
	
	getMBSelectionInteraction: function() 
	{
		return Ametys.tool.Tool.MB_TYPE_NOSELECTION;
	},
	
	createPanel: function ()
	{
		this._tree = this._drawCacheStatisticsTree();
		return this._tree;
	},
	
	setParams: function (params)
	{
		this.callParent(arguments);
		this._siteName = params.siteName;
		
		var toolTitle = "{{i18n PLUGINS_WEB_ADMINISTRATOR_UITOOL_SITE_CACHE_STATISTICS_BACK_TITLE}}";
		toolTitle += params.siteTitle ? " " + params.siteTitle + " (" + this._siteName + ")" : this._siteName;
		this.setTitle(toolTitle);

		this._tree.getStore().setRoot({id: 'root'});
		this.refresh();
	},
	
	refresh: function ()
	{
		this.showRefreshing();
		
		this._tree.getRootNode().expand(false, Ext.bind(this.showRefreshed, this), this);
	},
	
	/**
	 * @private
	 * Draw the tree panel representing the cache statistics
	 * @return a tree panel
	 */
	_drawCacheStatisticsTree: function()
    {
        var columns = [{
            xtype: 'treecolumn',
            text: "{{i18n PLUGINS_WEB_ADMINISTRATOR_CACHE_BACK_STATISTICS_COL_FIRST}}",
            stateId: 'grid-label', 
            dataIndex: 'label',
            flex: 1
        }, {
            text: "{{i18n PLUGINS_WEB_ADMINISTRATOR_CACHE_BACK_STATISTICS_FIRST_ROWHD_PAGE}}",
            columns: [{
                header: "{{i18n PLUGINS_WEB_ADMINISTRATOR_CACHE_BACK_STATISTICS_COL_PAGE_HITS}}",
                stateId: 'grid-page-hits', 
                dataIndex: 'pageHits', 
                align: 'center'
            }]
        }, {
            text: "{{i18n PLUGINS_WEB_ADMINISTRATOR_CACHE_BACK_STATISTICS_FIRST_ROWHD_PAGE_ELEMENT}}",
            columns: [{
                header: "{{i18n PLUGINS_WEB_ADMINISTRATOR_CACHE_BACK_STATISTICS_COL_CACHEABLE}}",
                stateId: 'grid-cacheable',
                dataIndex: 'cacheable', 
                align: 'center' 
            }, {
                header: "{{i18n PLUGINS_WEB_ADMINISTRATOR_CACHE_BACK_STATISTICS_COL_EFFICIENCY}}",
                stateId: 'grid-eff',
                dataIndex: 'eff', 
                align: 'center' 
            }, {
                header: "{{i18n PLUGINS_WEB_ADMINISTRATOR_CACHE_BACK_STATISTICS_COL_HITS}}",
                stateId: 'grid-hits',
                dataIndex: 'hits', 
                align: 'center' 
            }, {
                header: "{{i18n PLUGINS_WEB_ADMINISTRATOR_CACHE_BACK_STATISTICS_COL_CACHE_HITS}}",
                stateId: 'grid-cache-hits',
                dataIndex: 'cacheHits', 
                align: 'center' 
            }]
        }];
        
        return Ext.create ('Ext.tree.Panel', {
            stateful: true,
            stateId: this.self.getName() + "$grid",
            
            rootVisible: false,
            
            dockedItems: {
                dock: 'top',
                ui: 'tool-hintmessage',
                xtype: 'component',
                html: "{{i18n PLUGINS_WEB_ADMINISTRATOR_CACHE_BACK_STATISTICS_HELP_TEXT}}"
            },
			
			columns: columns,
			
			store: Ext.create('Ext.data.TreeStore', {
				
				model: 'Ametys.plugins.web.administration.CacheStatisticsBackTool.CacheStatisticsBackEntry',
				root: {
					id: 'dummy',
					text : 'dummy',
					name: 'dummy',
					path: 'dummy',
					expanded: false
				},
				
				proxy: {
		        	type: 'ametys',
					plugin: 'web',
					url: '/administrator/sites/cache-statistics-back-tree.json',
		        	reader: {
		        		type: 'json'
		        	}
		        },
		        
				listeners: {
					'beforeload': Ext.bind(this._onBeforeLoad, this),
					'itemmouseenter': Ext.bind(this._createQtip, this)
				}
			}),
			
			scrollable: true,
			border: false
		});
	},
	
	/**
	 * @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)
    {
		Ext.QuickTips.unregister(el);

		var tooltipCfg = {
			target: el,
			id: el.id + '-tooltip',
			inribbon: false,
			text: node.get('tooltipText')
		}; 
		
		Ext.QuickTips.register(tooltipCfg);
	},
	
	/**
	 * @private
	 * Handle the before load event of the store in order to cancel the load request on the root node.
	 * Be careful, this is mandatory is our case only because we have an hidden root node, which automatically perform a load when the node is created.
	 * @param {Ext.data.TreeStore} store The tree store
	 * @param {Object} operation The Ext.data.operation.Operation object that will be passed to the Proxy to
	 * load the Store
	 */
	_onBeforeLoad: function(store, operation)
    {
		var node = operation.node,
		id = node != null ? node.getId() : null;
	
		// Cancel load
		if (!id || id === 'dummy')
		{
			return false;
		}
		
		var params = {};
		params.siteName = this._siteName;
		params.contexts = '';
		
		Ext.Array.each (this._contexts, function(context){
			params.contexts += context == '' ? context : '#' + context;
		});
		
		operation.setParams(Ext.apply(operation.getParams() || {}, params ));
    },
    
    /**
     * @private
     * Listener when a "modified" message has been sent out on the message bus
     * @param {Ametys.message.Message} message The message
     */
    _onModified: function(message)
    {	
    	var targets = message.getTargets(Ametys.message.MessageTarget.CACHE_CONTEXT);
    	if (targets.length > 0)
		{
    		this._contexts = Ametys.plugins.web.administration.CacheStatisticsBackContext.getActiveContexts();
			this._tree.getStore().load({node: this._tree.getRootNode()});
    	}
    }
});

Ext.define("Ametys.message.CacheStatisticsBackContextMessageTarget",
	{
	    override: "Ametys.message.MessageTarget",
	    statics: 
	    {
	        /**
	         * @member Ametys.message.MessageTarget
	         * @readonly
	         * @property {String} CACHE_CONTEXT The target of the message is the cache's context 
	         */
	        CACHE_CONTEXT: "cacheContext"
	    }
	}
);