/*
 *  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 newsletters tree.
 * @private
 */
Ext.define('Ametys.plugins.newsletter.NewslettersTool', {
	extend: 'Ametys.tool.Tool',
	
	/**
	 * @property {Ext.tree.Panel} _tree The tree of this tool
	 * @private
	 */
	
	constructor: function(config)
	{
		this.callParent(arguments);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.CREATED, this._onMessageCreated, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onMessageModified, this);
		Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onMessageDeleted, this);
	},
	
	createPanel: function()
	{
		this._tree = Ext.create('Ametys.plugins.newsletter.NewslettersTree', {
			cls: 'newsletters-tool'
		});
		
		this._tree.on('selectionchange', this.sendCurrentSelection, this);
		this._tree.on('itemdblclick', this._openContent, this);
		
		return this._tree;
	},
	
	getMBSelectionInteraction: function() {
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},
	
	sendCurrentSelection: function()
	{
        var target = null;
        
		var selection = this._tree.getSelection();
		if (selection != null && selection.length >= 1)
		{
    		var node = selection[0];
    		var type = node.get('type');
    		if (type == 'newsletter-category-provider')
    		{
                target = {
        			id: Ametys.message.MessageTarget.NEWSLETTER_CATEGORY_PROVIDER,
        			parameters: {
        				id: node.get('id'),
        				lang: this._tree.getLang(),
        				mode: node.get('mode')
        			}
                }
    		}
    		else if (type == 'newsletter-category')
    		{
                target = {
        			id: Ametys.message.MessageTarget.NEWSLETTER_CATEGORY,
        			parameters: {
        				ids: [node.get('id')]
        			}
                }
    		}
    		else if (type == 'newsletter')
    		{
                target = {
        			id: Ametys.message.MessageTarget.CONTENT,
        			parameters: {
        				ids: [node.get('id')]
        			}
                }
    		}
        }
		
		Ext.create("Ametys.message.Message", {
			type: Ametys.message.Message.SELECTION_CHANGED,
			targets: target
		});
	},
	
	setParams: function(params)
	{
		this.callParent(arguments);
		this.showOutOfDate();
	},
	
	refresh: function()
	{
		this.showRefreshing();
		
		this._tree.refreshNode(this._tree.getRootNode(), Ext.bind(this.showRefreshed, this));
	},
	
	/**
     * Listener on creation message.
     * @param {Ametys.message.Message} message The creation message.
     * @private
     */
	_onMessageCreated: function(message)
	{
		// Case category or provider
		var target = message.getTarget(function(target) {
			return target.getId() == Ametys.message.MessageTarget.NEWSLETTER_CATEGORY 
				|| target.getId() == Ametys.message.MessageTarget.NEWSLETTER_CATEGORY_PROVIDER;
		});
		if (target != null)
		{
			// Refresh parent node
			var parentId = target.getParameters().parentId;
			var parentNode = this._tree.getStore().getNodeById(parentId);
			this._tree.refreshNode(parentNode);
		}
		
		// Case newsletter
		var target = message.getTarget(function(target) {
			return (target.getId() == Ametys.message.MessageTarget.CONTENT 
				&& target.getParameters().types[0] == "org.ametys.plugins.newsletter.Content.newsletter");
		});
		if (target != null)
		{
            var currentSelection = Ametys.message.MessageBus.getCurrentSelectionMessage().getTarget();
            // If the current selection is a category, assume the created target was
            // created under the currently selected category
            if (currentSelection != null && currentSelection.getId() == Ametys.message.MessageTarget.NEWSLETTER_CATEGORY)
            {
    			// Refresh selected node
    			var id = currentSelection.getParameters().id;
    			var node = this._tree.getStore().getNodeById(id);
    			this._tree.refreshNode(node);
            }
            // refresh everything, we don't know where the new item is in the tree
            else
            {
                this.showOutOfDate();
            }
		}
	},
	
	/**
     * Listener on edition message.
     * @param {Ametys.message.Message} message The edition message.
     * @private
     */
	_onMessageModified: function(message)
	{
		var target = message.getTarget(function(target) {return target.getId() == Ametys.message.MessageTarget.NEWSLETTER_CATEGORY;});
		if (target != null)
		{
			var categoryId = target.getParameters().id;
			
			Ametys.cms.newsletter.CategoryDAO.getCategory(
 					[categoryId], 
 					this._updateNode, 
 					{scope: this}
 			);
		}
	},
	
	/**
     * Listener on deletion message.
     * @param {Ametys.message.Message} message The deletion message.
     * @private
     */
	_onMessageDeleted: function(message)
	{
		var target = message.getTarget(function(target) {return target.getId() == Ametys.message.MessageTarget.NEWSLETTER_CATEGORY 
															|| target.getId() == Ametys.message.MessageTarget.NEWSLETTER_CATEGORY_PROVIDER 
															|| target.getId() == Ametys.message.MessageTarget.CONTENT && target.getParameters().types[0] == "org.ametys.plugins.newsletter.Content.newsletter";});
		if (target != null)
		{
			var node = this._tree.getStore().getNodeById(target.getParameters().id);
            if (node != null)
            {
    			var parentNode = this._tree.getStore().getNodeById(node.get('parentId'));
    			
    			// Select parent node and remove the node from the store
    			this._tree.getSelectionModel().select(parentNode);
    			node.remove();
            }
		}
	},
	
	/**
	 * Opens the selected newsletter.
	 * @param {Ext.view.View} view The view.
	 * @param {Ext.data.Model} record The record that belongs to the item.
	 * @private
	 */
	_openContent: function(view, record)
	{
		if (record.isRoot() || record.get('type') != 'newsletter')
		{
			return;
		}
		
		var params = {id: record.get('id')};
		
		Ametys.tool.ToolsManager.openTool('uitool-content', params);
	},
	
	/**
	 * Updates a node which has been edited with informations returned by the server.
	 * @param {Ametys.cms.newsletter.NewsletterCategory} category The newsletter category
	 * @private
	 */
	_updateNode: function(category)
	{
		var id = category.getId();
		var node = this._tree.getStore().getNodeById(id);
		
		node.beginEdit();
        node.set('text', category.getTitle());
        node.set('description', category.getDescription());
        node.set('template', category.getTemplate());
        node.endEdit();
        node.commit();
        
        // FIXME this._tree.getStore().sort() not working currently. See https://www.sencha.com/forum/showthread.php?301322-Tree-editing-and-auto-sort-Bug-or-missing-feature
        // Below is a temporary workaround.
        var sorters = this._tree.getStore().getSorters().getRange();
		this._tree.getStore().getSorters().clear();
		this._tree.getStore().sort(sorters);
	}
	
});