/*
 *  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 directories and allows to perform several operations such as : creating, updating, deleting, or change the priority of a link.
 */
Ext.define('Ametys.plugins.linkdirectory.link.LinkDirectoryTool', {
    extend: 'Ametys.tool.Tool',
    
    /**
     * @private
     * @property {Ext.grid.Panel} _grid The directory grid
     */
    
    /**
     * The constructor for the tool
     * @param {Object} config The initial configuration
     */
    constructor: function(config)
    {
        this.callParent(arguments);
        
        Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onLinkDeleted, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onLinkCreatedOrModified, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.CREATED, this._onLinkCreatedOrModified, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.MOVED, this._onLinkMoved, this);
    },
    
    /**
     * Get the type of selection for the tool.
     * @return the Type of selection
     */
    getMBSelectionInteraction: function() 
    {
        return Ametys.tool.Tool.MB_TYPE_ACTIVE;
    },
    
    /**
     * Create the tool panel
     * @return {Ext.grid.Panel} The link grid
     */
    createPanel: function ()
    {
    	this._grid = Ext.create('Ametys.plugins.linkdirectory.link.LinkDirectoryGrid', {
    		columns: [
                {stateId: 'grid-column-url', header: "{{i18n PLUGINS_LINKDIRECTORY_UITOOL_URL}}", sortable: false, groupable: false, width: 160, dataIndex: 'url', renderer: Ametys.plugins.linkdirectory.link.LinkDirectoryGrid.renderUrl},
                {stateId: 'grid-column-status', header: "{{i18n PLUGINS_LINKDIRECTORY_UITOOL_STATUS}}", sortable: false, width: 60, dataIndex: 'status', renderer: Ametys.plugins.linkdirectory.link.LinkDirectoryGrid.renderStatus},
                {stateId: 'grid-column-title', header: "{{i18n PLUGINS_LINKDIRECTORY_UITOOL_TITLE}}", sortable: false, groupable: false, width: 100, dataIndex: 'title'},
                {stateId: 'grid-column-alternative', header: "{{i18n PLUGINS_LINKDIRECTORY_UITOOL_ALTERNATIVE}}", sortable: false, groupable: false, width: 100, dataIndex: 'alternative'},
                {stateId: 'grid-column-themes', header: "{{i18n PLUGINS_LINKDIRECTORY_UITOOL_THEMES}}", sortable: false, width: 100, groupable: true, dataIndex: 'themes', renderer: Ext.bind(Ametys.plugins.linkdirectory.link.LinkDirectoryGrid.renderThemes, null, ['themes'], true)},
                {stateId: 'grid-column-visibility', header: "{{i18n PLUGINS_LINKDIRECTORY_UITOOL_DEFAULT_HIDDEN}}", sortable: false, width: 60, dataIndex: 'defaultHidden', renderer: Ametys.grid.GridColumnHelper.renderBooleanTrueIcon},
                {stateId: 'grid-column-restricted', header: "{{i18n PLUGINS_LINKDIRECTORY_UITOOL_LIMITED_ACCESS}}", sortable: false, groupable: false, width: 60, dataIndex: 'isRestricted', renderer: Ametys.grid.GridColumnHelper.renderBooleanTrueIcon}
            ]
    	});
		this._grid.on('selectionchange', this.sendCurrentSelection, this);
		
        return this._grid;
    },
    
    /**
     * Set the tool parameters
     * @param {Object} params the parameters
     * @param {String[]} [params.selectedLinkIds] The id of links to select at opening
     */ 
    setParams: function (params)
    {
        this.callParent(arguments);
        this.refresh();
        
        this._initialSelectedLinkIds = params.selectedLinkIds || [];
    },
    
    sendCurrentSelection: function()
    {
    	var selection = this._grid.getSelectionModel().getSelection();

		var ids = [];
		for (var i = 0; i < selection.length; i++) 
		{
			ids.push(selection[i].id);
		}
		
		if (ids.length > 0)
		{
			Ext.create('Ametys.message.Message', {
				type: Ametys.message.Message.SELECTION_CHANGED,
				targets: {
					id: Ametys.message.MessageTarget.LINK_DIRECTORY,
					parameters: {
						ids: ids
					}
				}
			});
		}
		else
		{
			Ext.create('Ametys.message.Message', {
				type: Ametys.message.Message.SELECTION_CHANGED,
				targets: []
			});
		}
    },
    
    refresh: function ()
    {
		this.showRefreshing();
		this._grid.getStore().load({callback: this._refreshCb, scope: this});
    },
    
    /**
     * Function invoked after loading the store
     * @private
     */
    _refreshCb: function ()
    {
    	this.showRefreshed();
    	
    	if (this._initialSelectedLinkIds.length > 0)
    	{
    		var records = [];
    		var sm = this._grid.getSelectionModel();
    		var store = this._grid.getStore();
    		
    		Ext.Array.each (this._initialSelectedLinkIds, function (id) {
    			var index = store.find("id", id); 
                if (index != -1)
                {
                	records.push(store.getAt(index));
                }
    		});
    		
    		sm.select(records);
    		
    		this._initialSelectedLinkIds = []; // reset
    	}
    },
    
    /**
     * Get the current language of the tool
     * @return {String} the current selected language
     */
    getCurrentLanguage: function()
    {
    	return this._grid.down("combobox[itemId='languages-combo']").getValue();
    },
    
    //----------------------------------------------------------------------------
    /**
     * @private
     * Listener upon reception of a creation message 
     * @param {Ametys.message.Message} message the creation message
     */
    _onLinkCreatedOrModified: function(message)
    {
        var targets = message.getTargets(Ametys.message.MessageTarget.LINK_DIRECTORY);
        if (targets.length > 0)
        {
            this.showOutOfDate();
        }
    },
    
    /**
     * @private
     * Listener upon reception of a deletion message
     * @param {Ametys.message.Message} message the deletion message
     */
    _onLinkDeleted: function(message)
    {
        var targets = message.getTargets(Ametys.message.MessageTarget.LINK_DIRECTORY);
        if (targets.length > 0)
        {
            var store = this._grid.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
     */
    _onLinkMoved: function(message)
    {
    	var targets = message.getTargets(Ametys.message.MessageTarget.LINK_DIRECTORY);
        if (targets.length > 0)
        {
            this.showOutOfDate();
        }
    }
});