/*
 *  Copyright 2016 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.
 */
 
/**
 * @private
 * This tool lists all existing orphan forms
 */ 
Ext.define('Ametys.plugins.forms.content.tool.OrphanFormsTool', {
	
	extend: 'Ametys.tool.Tool',
	
    /**
     * @property {Number} [PAGE_SIZE=50] The number of records to display by 'page'
     * @readonly
     */
    PAGE_SIZE: 50,
	
    
    constructor: function(config)
    {
    	this.callParent(arguments);

    	Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onDeleted, this);
    },
    
	createPanel: function()
	{
		this._store = Ext.create('Ext.data.Store', {
			model: 'Ametys.plugins.forms.content.tool.OrphanFormsTool.OrphanForm',
			
		    pageSize: this.PAGE_SIZE,
		    totalProperty: 'total', 
		    
		    proxy: {
	        	type: 'ametys',
				plugin: 'forms',
				url: 'orphan-forms.json',
	        	reader: {
	        		type: 'json',
					rootProperty: 'tables'
	        	},
	        }
		});
		
		this._grid = new Ext.grid.GridPanel({
            stateful: true,
            stateId: this.self.getName() + "$grid",

            store : this._store,
            
            selModel : {
                mode: 'MULTI'
            },
            
            listeners: {
                'selectionchange': Ext.bind(this.sendCurrentSelection, this)
            },
	        
	        viewConfig: {
	        	forceFit: true
	        },
	        
	        columns: [
	                  {header: "{{i18n PLUGINS_FORMS_ADMINISTRATOR_ORPHAN_FORMS_COL_NAME}}", flex: 1, dataIndex: 'name'},
	                  {header: "{{i18n PLUGINS_FORMS_ADMINISTRATOR_ORPHAN_FORMS_COL_TOTAL}}", width: 100, align: 'center', dataIndex: 'total'},
	                  {header: "{{i18n PLUGINS_FORMS_ADMINISTRATOR_ORPHAN_FORMS_COL_CONTENT_TITLE}}", width: 250, dataIndex: 'contentTitle'},
	                  {header: "{{i18n PLUGINS_FORMS_ADMINISTRATOR_ORPHAN_FORMS_COL_STILL_EXISTS}}", width: 100, align: 'center', dataIndex: 'stillExists', renderer: Ametys.grid.GridColumnHelper.renderBooleanTrueIcon},
	                  {header: "{{i18n PLUGINS_FORMS_ADMINISTRATOR_ORPHAN_FORMS_COL_SITE_NAME}}", width: 100, dataIndex: 'siteName'},
	                  {header: "{{i18n PLUGINS_FORMS_ADMINISTRATOR_ORPHAN_FORMS_COL_LAST_CONTRIBUTOR}}", width: 250, dataIndex: 'lastContributor'}
	              ]
	    });
		
		return this._grid;
	},
	
	setParams: function()
	{
		this.callParent(arguments);
		this.refresh();
	},
	
	getMBSelectionInteraction: function() 
	{
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},
	
	
	sendCurrentSelection : function()
    {
		var targets = [];
        Ext.each (this._grid.getSelectionModel().getSelection(), function (record) {
        	targets.push({
        		id: Ametys.message.MessageTarget.TABLE,
                parameters: {
                	name: record.data.name
                }
        	});
        });
        
        Ext.create("Ametys.message.Message", {
            type: Ametys.message.Message.SELECTION_CHANGED,
            targets: targets
        });
    },
	
	refresh: function ()
	{
		this.showRefreshing();
		this._store.load({callback: this.showRefreshed, scope: this});
	},
    
    /**
     * @private
     * Listener function invoked whenever a a deleted message is fired
     * @param {Ametys.message.Message} message the deletion message
     */
    _onDeleted: function(message)
    {
    	var targets = message.getTargets(Ametys.message.MessageTarget.TABLE);
        if (targets.length > 0)
        {
            this.showOutOfDate();
        }
    }
});

Ext.define("Ametys.message.OrphanFormsMessageTarget", {
	override: "Ametys.message.MessageTarget",
	
	statics: 
	{
		/**
		 * @member Ametys.message.MessageTarget
		 * @readonly
		 * @property {String} TABLE The target type is an orphan table
		 * @property {String} TABLE.name The name of the orphan table
		 */
		TABLE: "table"
	}
});