/*
 *  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 list of aliases and allows to perform several operations such as : creating, updating, deleting, or change the priority of an alias.
 */
Ext.define('Ametys.plugins.web.alias.AliasTool', {
	extend: 'Ametys.tool.Tool',
	
	/**
	 * @private
	 * @property {Ext.grid.Panel} _aliasGrid The alias grid
	 */
	
	constructor: function(config)
	{
		this.callParent(arguments);
		Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onAliasDeleted, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onAliasCreatedOrModified, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.CREATED, this._onAliasCreatedOrModified, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.MOVED, this._onAliasMoved, this);
	},
	
	getMBSelectionInteraction: function() 
	{
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},
	
	createPanel: function ()
	{
		this._aliasGrid = this._drawAliasPanel();
		return this._aliasGrid;
	},
	
	setParams: function (params)
	{
		this.callParent(arguments);
		this._initialSelectedAliasIds = params.selectedAliasIds || [];
		
		this.refresh();
	},
	
	sendCurrentSelection: function()
	{
		var targets = [];
		var store = this._aliasGrid.getStore();
		
		var selectedAliases = this._aliasGrid.getSelectionModel().getSelection();
		Ext.Array.forEach(selectedAliases, function(selectedAlias) {
			var id = selectedAlias.id;
			target = Ext.create('Ametys.message.MessageTarget', {
				id: Ametys.message.MessageTarget.ALIAS,
				parameters: {
					id: selectedAlias.id, 
					index: store.find('id', id), 
					size: store.getTotalCount()
				}
			});
			
			targets.push(target);
		});
		
		Ext.create('Ametys.message.Message', {
			type: Ametys.message.Message.SELECTION_CHANGED,
			targets: targets
		});
	},
	
	refresh: function ()
	{
		this.showRefreshing();
		this._aliasGrid.getStore().load({callback: this._refreshCb, scope: this});
	},
	
	/**
     * Function invoked after loading the store
     * @private
     */
    _refreshCb: function ()
    {
    	this.showRefreshed();
    	
    	if (this._initialSelectedAliasIds.length > 0)
    	{
    		var records = [];
    		var sm = this._aliasGrid.getSelectionModel();
    		var store = this._aliasGrid.getStore();
    		
    		Ext.Array.each (this._initialSelectedAliasIds, function (id) {
    			var index = store.find("id", id); 
                if (index != -1)
                {
                	records.push(store.getAt(index));
                }
    		});
    		
    		sm.select(records);
    		
    		this._initialSelectedAliasIds = []; // reset
    	}
    },
	
	/**
	 * @private
	 * Draw the grid panel showing the aliases
	 * @return {Ext.grid.Panel} The grid panel
	 */
	_drawAliasPanel: function()
	{
		var store = Ext.create('Ext.data.Store', {
			model: 'Ametys.plugins.web.alias.AliasTool.Alias',
	        groupField: 'expired',
	        
	        proxy: {
	        	type: 'ametys',
				plugin: 'web',
				url: 'alias/list.json',
	        	reader: {
	        		type: 'json',
					rootProperty: 'alias'
	        	},
	        	
	        	extraParams: {
					siteName: Ametys.getAppParameter('siteName')
				}
	        },
	        
	        listeners: {
	        	'load': Ext.bind(this.sendCurrentSelection, this)
	        }
		});		
		
		return Ext.create('Ext.grid.Panel', {
			stateful: true,
			stateId: this.self.getName() + "$grid",

			store : store,
			
			selModel : {
		    	mode: 'MULTI'
		    },
		    
		    listeners: {
		    	'selectionchange': Ext.bind(this.sendCurrentSelection, this)
		    },
		    
		    features: [{
		        groupHeaderTpl: ['{name}'],
		        ftype: 'grouping'
		    }],
			
		    columns: [
		        {stateId: 'grid-origin', header: "{{i18n PLUGINS_WEB_ALIAS_UITOOL_ORIGIN}}", width : 270, sortable: true, dataIndex: 'url'},
		        {stateId: 'grid-target', header: "{{i18n PLUGINS_WEB_ALIAS_UITOOL_TARGET}}", width : 270, sortable: true, dataIndex:'targetUrl', renderer: Ext.bind(this._renderTargetUrl, this)},
		        {stateId: 'grid-expirationDate', header: "{{i18n PLUGINS_WEB_ALIAS_UITOOL_EXPIRATION_DATE}}", width : 160, sortable: true, dataIndex: 'expirationDate', renderer: Ext.util.Format.dateRenderer('d F Y')},
		        {stateId: 'grid-status', header: "{{i18n PLUGINS_WEB_ALIAS_UITOOL_STATUS}}", width : 160, hidden: true, sortable: true, dataIndex: 'expired', renderer: Ext.bind(this._renderExpired, this)}
		    ]
		});
	},
	
	/**
	 * @private
	 * Render the target url in the aliases grid
	 * @param {String} value the value of the target url
	 */
	_renderTargetUrl: function (value)
	{
		if (value == 'unknown')
		{
			return '<span style="color: #666; font-style: italic">' + "{{i18n PLUGINS_WEB_HANDLE_ALIAS_UNKNOWN_PAGE}}" + '</span>'
		}
		
		return value;
	},
	
	/**
	 * @private
	 * Render the expired column of the grid
	 * @param {String} value the value of 'expired'
	 */
	_renderExpired: function (value)
	{
		if (value)
		{
			return '<img src="' + Ametys.getPluginResourcesPrefix('web') + "/img/alias/expired_13.png" + '" style="float:left; margin-right: 5px"/>' + "{{i18n PLUGINS_WEB_ALIAS_UITOOL_STATUS_EXPIRED}}";
		}
		
		return '<img src="' + Ametys.getPluginResourcesPrefix('web') + "/img/alias/active_13.png" + '" style="float:left; margin-right: 5px"/>' + "{{i18n PLUGINS_WEB_ALIAS_UITOOL_STATUS_ACTIVE}}";
	},
	
	/**
	 * @private
	 * Listener upon reception of a creation message 
	 * @param {Ametys.message.Message} message the creation message
	 */
	_onAliasCreatedOrModified: function(message)
	{
		var targets = message.getTargets(Ametys.message.MessageTarget.ALIAS);
		if (targets.length > 0)
		{
			this.showOutOfDate();
		}
	},
	
	/**
	 * @private
	 * Listener upon reception of a deletion message
	 * @param {Ametys.message.Message} message the deletion message
	 */
	_onAliasDeleted: function(message)
	{
		var targets = message.getTargets(Ametys.message.MessageTarget.ALIAS);
		if (targets.length > 0)
		{
			var store = this._aliasGrid.getStore();
			Ext.Array.forEach(targets, function(target) {
				var id = target.getParameters().id;
				var index = store.find("id", id); 
				if (index != -1)
				{
					store.removeAt(index);
				}
			});
		}
	},
	
	/**
	 * @private
	 * Listener upon reception of a moved message
	 * @param {Ametys.message.Message} message the deletion message
	 */
	_onAliasMoved: function(message)
	{
		this.refresh();
	}
});

Ext.define("Ametys.message.AliasMessageTarget",{
	override: "Ametys.message.MessageTarget",
	statics: 
	{
		/**
		 * @member Ametys.message.MessageTarget
		 * @readonly
		 * @property {String} ALIAS The target of the message is an alias 
		 */
		ALIAS: "alias"
	}
});