/*
 *  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 subscribers of a category.
 * @private
 */
Ext.define('Ametys.plugins.newsletter.subscribers.SubscribersTool', {
	extend: 'Ametys.tool.Tool',
	
	/**
	 * @property {String} _categoryId id of the current category
	 * @private
	 */
	
	/**
	 * @property {Ext.grid.Panel} _grid The grid of this tool
	 * @private
	 */
	
	/**
	 * @property {Ext.grid.Panel} _mainPanel The main panel of this tool. Only displays the grid OR the noselection panel, depending on the selection.
	 * @private
	 */
	
    /**
     * @property {Number} PAGE_SIZE The number of records to display by 'page'
     * @readonly
     */
    PAGE_SIZE: 100,
    
	constructor: function(config)
	{
		this.callParent(arguments);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onMessageModified, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.SELECTION_CHANGED, this._onSelectionChange, this);
	},
	
	createPanel: function()
	{
		var store = Ext.create('Ext.data.Store', {
            remoteSort: true,
			model: 'Ametys.plugins.newsletter.subscribers.SubscribersTool.SubscriberEntry',
			proxy: {
				type: 'ametys',
				plugin: 'newsletter',
				url: 'subscribers.json',
				reader: {
					type: 'json',
					rootProperty: 'subscribers'
				},
				extraParams: {
					siteName: Ametys.getAppParameter('siteName')
				}
			},
			
			sorters: [{
				property: 'email',
				direction: 'ASC'
			}],
			
			pageSize: this.PAGE_SIZE,
		    totalProperty: 'total' 
		});
		store.on('beforeload', this._onBeforeLoad, this);
		
		this._grid = Ext.create('Ext.grid.Panel', {
			store: store,
			
			selModel: {
				mode: "MULTI"
			},
			
			region: 'center',
			
			stateful: true,
			stateId: this.self.getName() + "$grid",
			columns: [
				{stateId: 'grid-column-email', header: "{{i18n PLUGINS_NEWSLETTER_SUBSCRIBERS_COLUMN_EMAIL}}", width: 400, sortable: true, dataIndex: 'email', hideable: false},
		        {stateId: 'grid-column-subscribedat', header: "{{i18n PLUGINS_NEWSLETTER_SUBSCRIBERS_COLUMN_SUBSCRIBED_AT}}", width: 200, sortable: true, dataIndex: 'subscribedAt', renderer: Ametys.grid.GridColumnHelper.renderDate}
			],
			
			dockedItems: [{
                xtype: 'pagingtoolbar',
                store: store,
                dock: 'bottom',
                displayInfo: true,
                displayMsg: "{{i18n plugin.newsletter:PLUGINS_NEWSLETTER_UITOOL_SEARCH_CONTENT_RESULT_1}}{0}{{i18n plugin.newsletter:PLUGINS_NEWSLETTER_UITOOL_SEARCH_CONTENT_RESULT_2}}{1}{{i18n plugin.newsletter:PLUGINS_NEWSLETTER_UITOOL_SEARCH_CONTENT_RESULT_3}}{2}",
                emptyMsg: "{{i18n plugin.newsletter:PLUGINS_NEWSLETTER_UITOOL_SEARCH_NO_RESULT}}"
			}]
		});
		this._grid.on('selectionChange', this.sendCurrentSelection, this)
		
		return Ext.create('Ext.panel.Panel', {
			layout: 'card',
			activeItem: 0,
			cls: 'newsletter-subscribers-tool',
			items: [
				{
					xtype: 'component',
					cls: 'subscribers-no-selection',
					html: '{{i18n PLUGINS_NEWSLETTER_UITOOL_SUBSCRIBERS_SELECT_CATEGORY}}',
					border: false
				},
				this._grid
			]
		});
	},
	
	setParams: function(params)
	{
		this.callParent(arguments);
		
		this.refresh();
	},
	
	refresh: function()
	{
		this.showRefreshing();
		
		var target = Ametys.message.MessageBus.getCurrentSelectionMessage().getTarget(Ametys.message.MessageTarget.NEWSLETTER_CATEGORY);
		if (target != null)
		{
			this.setInMatchState(target.getParameters().id);
		}
		else
		{
			this.setNoSelectionMatchState();
		}
	},
	
	/**
	 * This function is called when the selection is empty or do not no match the excepted target.
	 */
	setNoSelectionMatchState: function()
	{
		this._categoryId = null;
		
		this.getContentPanel().getLayout().setActiveItem(0);
		this.showRefreshed();
	},
	
	/**
	 * This function is called when the selection matches the excepted target.
	 * @param {String} categoryId The current category id
	 */
	setInMatchState: function(categoryId)
	{
		this._categoryId = categoryId;
		
		this.getContentPanel().getLayout().setActiveItem(1);
		this._grid.getStore().load({
			callback: Ext.bind(this.showRefreshed, this)
		});
	},
	
	getMBSelectionInteraction: function()
	{
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},
	
	sendCurrentSelection: function()
	{
		if (this._categoryId != null)
		{
			var targets = [];
			var subtargets = [];
			
			var selection = this._grid.getSelection();
			if (selection && selection.length > 0)
			{
				Ext.Array.forEach(selection, function(record) {
					subtargets.push({
					    id: Ametys.message.MessageTarget.NEWSLETTER_SUBSCRIBER,
						parameters: {
							email: record.get('email')
						}
					});
				});
			}
			
			targets.push({
			    id: Ametys.message.MessageTarget.NEWSLETTER_CATEGORY,
				parameters: {
					ids: [this._categoryId]
				},
				subtargets: subtargets
			});
			
			Ext.create("Ametys.message.Message", {
				type: Ametys.message.Message.SELECTION_CHANGED,
				targets: targets
			});
		}
	},
	
	/**
	 * Function before loading the store
	 * Set parameters to be passed to the request.
	 * @param {Ext.data.Store} store The store
	 * @param {Ext.data.operation.Operation} operation The object that will be passed to the Proxy to load the store
	 * @private
	 */
	_onBeforeLoad: function(store, operation)
	{
		operation.setParams(Ext.apply(operation.getParams() || {}, {
			categoryID: this._categoryId
		}));
	},
	
	/**
	 * Selection change listener.
	 * Update the state of the tool given the incoming message.
	 * @param {Ametys.message.Message} message The listened message
	 */
	_onSelectionChange: function(message)
	{
		var target = message.getTarget(Ametys.message.MessageTarget.NEWSLETTER_CATEGORY);
		if (target == null)
		{
			// No more target
			this.setNoSelectionMatchState();
		}
		else if (this._categoryId != target.getParameters().id)
		{
			this._categoryId = target.getParameters().id;
			// Major out-of-date
			this.showOutOfDate(true);
		}
		else
		{
			this.showUpToDate();
		}
	},
	
	/**
	 * Listener on edition message.
	 * @param {Ametys.message.Message} message The edition message.
	 */
	_onMessageModified: function(message)
	{
		var target = message.getTarget(Ametys.message.MessageTarget.NEWSLETTER_CATEGORY);
		if (target != null && this._categoryId == target.getParameters().id)
		{
			this.showOutOfDate(true);
		}
	}
});

Ext.define('Ametys.plugins.newsletter.subscribers.SubscribersTool.SubscriberEntry', { 
	extend: 'Ext.data.Model',
	
	fields: [
		'email',
		'siteName',
		'category',
		{name: 'subscribedAt', type:'date'}
	]
});