/*

 *  Copyright 2019 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 all queries in READ access for current user
 * @private
 */
Ext.define('Ametys.plugins.queriesdirectory.tool.QueriesTool', {
	extend: "Ametys.tool.Tool",
    
    /**
     * @property {Ext.tree.Panel} _tree The tree panel displaying the queries
     * @private
     */ 
    /**
     * @property {Ametys.message.MessageTarget[]} _previousSelection The previous selection, to transmit to the queries
     * @private
     */
	
	constructor: function(config)
	{
		this.callParent(arguments);

		Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onDeletionMessage, this);
	},

    setParams: function (params)
    {
        this.callParent(arguments);
        this.showRefreshing();
        this._tree.initRootNodeParameter(Ext.bind(this._refreshCb, this));
    },
    
    /**
     * @private
     * Callback function after (re)loading the tree
     */
    _refreshCb: function ()
    {
        this.showRefreshed();
        
        // Select root node
        this._tree.getSelectionModel().select(0);
    },
    
	getMBSelectionInteraction: function() 
	{
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},

    onFocus: function()
    {
        this._previousSelection = Ametys.message.MessageBus.getCurrentSelectionMessage().getTargets();
        Ametys.plugins.queriesdirectory.tool.QueriesTool.superclass.onFocus.call(this);
    },

	sendCurrentSelection: function()
	{
        var selection = this._tree.getSelectionModel().getSelection();
        var queryIds = selection
            .filter(function(record) {
                return record.get('isQuery');
            })
            .map(function(record) {
                return record.getId();
            });
        
        var queryTargets = [{
            id: Ametys.message.MessageTarget.QUERY,
            parameters: { 
                ids: queryIds,
                selection: this._previousSelection || null
            }
        }];
        
        var queryContainerTargets = selection
            .filter(function(record) {
                return !record.get('isQuery');
            })
            .map(function(record) {
                return {
                    id: Ametys.message.MessageTarget.QUERY_CONTAINER,
                    parameters: {
                        id: record.getId(),
                        canRead: record.get('canRead'),
                        canWrite: record.get('canWrite'),
                        canRename: record.get('canRename'),
                        canDelete: record.get('canDelete'),
                        canAssignRights: record.get('canAssignRights'),
                        fullPath: record.getFullPath(),
                        name: record.get('text')
                    }
                };
            });
        
        var targets = Ext.Array.merge(queryTargets, queryContainerTargets);
		
		Ext.create("Ametys.message.Message", {
			type: Ametys.message.Message.SELECTION_CHANGED,
			targets: targets
		});
	},

	createPanel: function()
    {
        this._tree = Ext.create("Ametys.plugins.queriesdirectory.tree.QueriesTree", { 
            rootVisible: true,
            stateful: true,         
            stateId: this.self.getName() + "$tree",     
            scrollable: true,
            
            cls: 'queries-uitool',
            
            columns: [
                  {
                      xtype: 'treecolumn', 
                      header: "{{i18n PLUGINS_QUERIESDIRECTORY_UITOOL_QUERIES_COLUMN_TITLE}}", 
                      flex: 100, 
                      sortable: true, 
                      dataIndex: 'text', 
                      renderer: Ametys.plugins.queriesdirectory.tree.QueriesTree.renderTitle,
                      editor: {
                          xtype: 'textfield',
                          allowBlank: false,
                          selectOnFocus: true
                      }
                  },
                  {header: "{{i18n PLUGINS_QUERIESDIRECTORY_UITOOL_QUERIES_COLUMN_TYPE}}", width: 70, sortable: true, dataIndex: 'type', renderer: Ametys.plugins.queriesdirectory.tree.QueriesTree.renderType},
                  {header: "{{i18n PLUGINS_QUERIESDIRECTORY_UITOOL_QUERIES_COLUMN_DESCRIPTION}}", hidden: true, width: 180, sortable: true, dataIndex: 'description', renderer: Ametys.plugins.queriesdirectory.tree.QueriesTree.renderDescription},
                  {header: "{{i18n PLUGINS_QUERIESDIRECTORY_UITOOL_QUERIES_COLUMN_DOCUMENTATION}}", hidden: true, width: 180, sortable: true, dataIndex: 'documentation', renderer: Ametys.plugins.queriesdirectory.tree.QueriesTree.renderDocumentation},
                  {header: "{{i18n PLUGINS_QUERIESDIRECTORY_UITOOL_QUERIES_COLUMN_AUTHOR}}", hidden: false, width: 110, sortable: true, dataIndex: 'authorFullName'},
                  {header: "{{i18n PLUGINS_QUERIESDIRECTORY_UITOOL_QUERIES_COLUMN_CONTRIBUTOR}}", hidden: false, width: 110, sortable: true, dataIndex: 'contributorFullName'},
                  {header: "{{i18n PLUGINS_QUERIESDIRECTORY_UITOOL_QUERIES_COLUMN_CREATIONDATE}}", hidden: true, width: 110, sortable: true, dataIndex: 'creationDate', renderer: Ext.util.Format.dateRenderer(Ext.Date.patterns.FriendlyDateTime)},
                  {header: "{{i18n PLUGINS_QUERIESDIRECTORY_UITOOL_QUERIES_COLUMN_LASTMODIFICATIONDATE}}", hidden: true, width: 110, sortable: true, dataIndex: 'lastModificationDate', renderer: Ext.util.Format.dateRenderer(Ext.Date.patterns.FriendlyDateTime)}
            ],
            
            selModel : {
                mode: 'MULTI'
            },

            listeners: {                
                selectionchange: this.sendCurrentSelection,
                itemdblclick: {
                    fn: function(view, record, item, index)
                    {
                        if (record.get('isQuery') === true && !(record.get('type') === "formatting"))
                        {
                            this._executeQuery(view, record, item, index);
                        }
                    }
                },
                scope: this
            }
        });
        return this._tree;
    },
	
	/**
	 * Listener on double-click. Executes the query.
	 * @param {Ext.view.View} view The view
	 * @param {Ext.data.Model} record The record that belongs to the item
	 * @param {HTMLElement} item The item's element
	 * @param {Number} index The item's index 
	 * @private
	 */	
	_executeQuery: function(view, record, item, index)
	{
        var type = record.get('type');
        var content = record.get('content');
        var title = record.get('text');
        
        var readOnly = !record.get('canWrite');
        
        var query = Ametys.plugins.queriesdirectory.model.QueryFactory.create(type, record.getId(), content, title, readOnly);
        
        if (this._previousSelection)
        {
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.SELECTION_CHANGED,
                targets: this._previousSelection,
                callback: function() {
                    query.execute();
                }
            });
        }
        else
        {
            query.execute();
        }
	},
	
	refresh: function()
	{
		this.showRefreshing();

        Ametys.plugins.queriesdirectory.QueriesDAO.invalidateCache();
        
		this._tree.getStore().load({
			scope: this,
			callback: this.showRefreshed
		});
	},
	
	/**
	 * Listener on deletion messages
	 * @param {Ametys.message.Message} message The deletion message.
	 * @private
	 */
	_onDeletionMessage: function (message)
	{
		var targets = message.getTargets(function(target) {
            return target.getId() == Ametys.message.MessageTarget.QUERY || target.getId() == Ametys.message.MessageTarget.QUERY_CONTAINER
        });
		if (targets.length == 1)
		{
            this._tree.reloadParent(targets[0], false);
        }
        else if (targets.length > 1)
        {
			this.showOutOfDate();
		}
	}
});