/*
 *  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 catalogs.
 * @private
 */
Ext.define('Ametys.plugins.odf.catalog.CatalogsTool', {
	extend: 'Ametys.tool.Tool',

	/**
	 * @private
	 * @property {Ext.grid.Panel} _grid The grid for catalogs
	 */
	
	/**
	 * @private
	 * @property {Ext.data.Store} _store The store for catalogs
	 */
	
	constructor: function(config)
	{
		this.callParent(arguments);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.CREATED, this._onMessageCreatedOrModified, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onMessageCreatedOrModified, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onMessageDeleted, this);
	},
	
	createPanel: function()
	{
		this._store = Ametys.odf.catalog.CatalogDAO.getStore();
		
		this._grid = Ext.create('Ext.grid.Panel', {
			
			stateful: true,
			stateId: this.self.getName() + "$grid",
			
			store: this._store,
			
			columns: [
	            {stateId: 'grid-column-title', header: "{{i18n PLUGINS_ODF_UITOOL_CATALOG_COLUMN_TITLE}}", flex: 1, sortable: true, dataIndex: 'title', renderer: this._renderTitle},
	            {stateId: 'grid-column-code', header: "{{i18n PLUGINS_ODF_UITOOL_CATALOG_COLUMN_CODE}}", width: 200, sortable: true, dataIndex: 'code'},
                {stateId: 'grid-column-default', header: "{{i18n PLUGINS_ODF_UITOOL_CATALOG_COLUMN_DEFAULT}}", width: 100, sortable: true, dataIndex: 'isDefault', renderer: Ametys.grid.GridColumnHelper.renderBooleanTrueIcon},
	            {stateId: 'grid-column-programs', header: "{{i18n PLUGINS_ODF_UITOOL_CATALOG_COLUMN_PROGRAMS}}", width: 100, sortable: true, dataIndex: 'nbPrograms'}
			],
			
			listeners: {
				'selectionchange': Ext.bind(this.sendCurrentSelection, this)
			}
		});
		
		return this._grid;
	},
	
	getMBSelectionInteraction: function()
	{
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},
	
	sendCurrentSelection: function()
	{
		var selection = this._grid.getSelection();
		
		var targets = [];
		Ext.Array.forEach(selection, function(item) {
			targets.push({
				id: Ametys.message.MessageTarget.ODF_CATALOG,
				parameters: {
					id: item.getId(),
					title: item.get('title')
				}
			});
		});
		
		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
     * When store is loaded
     * @param {Ext.data.Store} store The store
     * @param { Ext.data.Model[]} records The array of loaded records
     */
	_onLoad: function(store, records)
	{
		if (records.length == 0)
		{
			// No catalogs
			this._setGridMasked();
		}
		else
		{
			this._grid.unmask();
		}
	},
	
    /**
     * @private
     * Mask the grid
     */
	_setGridMasked: function()
	{
		this._grid.mask("{{i18n plugin.odf:PLUGINS_ODF_UITOOL_CATALOG_TOOL_NO_RESULT}}", 'ametys-mask-unloading');
	},
	
	/**
     * Listener on creation or edition message.
     * @param {Ametys.message.Message} message The edition message.
     * @private
     */
	_onMessageCreatedOrModified: function(message)
	{
		var targets = message.getTargets(Ametys.message.MessageTarget.ODF_CATALOG);
		if (targets.length > 0)
		{
			this.showOutOfDate();
		}
	},
	
	/**
     * Listener on deletion message.
     * @param {Ametys.message.Message} message The deletion message.
     * @private
     */
	_onMessageDeleted: function(message)
	{
		var targets = message.getTargets(Ametys.message.MessageTarget.ODF_CATALOG);
		for (var i = 0; i < targets.length; i++)
		{
			var record = this._store.getById(targets[i].getParameters().id);
			this._store.remove(record);
		}
		
		if (this._store.getCount() == 0)
		{
			this._setGridMasked();
		}
	},
	
	/**
	 * Renders the title column.
	 * @param {Object} value The data value for the current cell.
	 * @private
	 */
	_renderTitle: function(value)
	{
		return '<span class="a-grid-glyph odficon-book"></span>' + value;
	}
});