/*

 *  Copyright 2013 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 carts in READ access for current user
 * @private
 */
Ext.define('Ametys.plugins.cart.tool.CartsTool', {
	extend: "Ametys.tool.Tool",
	
	/**
	 * @property {Ext.grid.Panel} _grid The grid panel displaying the carts
	 * @private
	 */
	/**
	 * @property {Ext.data.Store} _store The cart store
	 * @private
	 */
	
	constructor: function(config)
	{
		this.callParent(arguments);
	},
	
	getMBSelectionInteraction: function() 
	{
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},
	
	sendCurrentSelection: function()
	{
		var cartIds = [];
		
		var selection = this._grid.getSelectionModel().getSelection();
		for (var i=0; i < selection.length; i++)
		{
			cartIds.push(selection[i].getId());
		}
		
		Ext.create("Ametys.message.Message", {
			type: Ametys.message.Message.SELECTION_CHANGED,
			
			targets: {
			    id: Ametys.message.MessageTarget.CART,
				parameters: { ids: cartIds }
			}
		});
	},
	
	setParams: function (params)
	{
		this.callParent(arguments);
		this.refresh();
	},
	
	createPanel: function()
	{
        this._grid = Ext.create("Ametys.plugins.cart.tool.CartsPanel", { 
			stateful: true,
			stateId: this.self.getName() + "$grid",
			enableDrop: true,
			listeners: {
				itemdblclick: {fn: this._openCart, scope: this},
				selectionchange: {fn: this.sendCurrentSelection, scope: this}
			}
		});
		
		return this._grid;
	},
	
	refresh: function()
	{
		this.showRefreshing();
		
		Ametys.plugins.cart.CartsDAO.invalidateCache();
		
		this._grid.getStore().load({
			scope: this,
			callback: this.showRefreshed
		});
	},
	
	/**
	 * Open the cart
	 * @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
	 */
	_openCart: function(view, record, item, index)
	{
		var cartId = record.getId();
		Ametys.tool.ToolsManager.openTool('uitool-cart', {id: cartId});
	}
});