/*
 *  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 class controls a ribbon button that will be responsible for a workflow action.
 * The button will be enabled only if the workflow action is available for current selection.
 * @private
 */
Ext.define('Ametys.plugins.cms.content.controller.PasteContentValuesController', {
	extend: 'Ametys.plugins.cms.content.controller.SmartContentController',
	
	constructor: function(config)
	{
		this.callParent(arguments);
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onModified, this);
	},
	
	/**
	 * Listener when the clipboard has been modified.
	 * Will update the state of the buttons effectively upon the current selection.
	 * @param {Ametys.message.Message} message The modified message.
	 * @protected
	 */
	_onModified: function (message)
	{
		message = message || Ametys.message.MessageBus.getCurrentSelectionMessage();
		
		var target = message.getTarget(Ametys.message.MessageTarget.CLIPBOARD); 
		if (target != null)
		{
			this.refresh();
		}
	},
	
	_getStatusCb: function (params, targets)
	{
		var copiedContent;
		var clipboardData = Ametys.clipboard.Clipboard.getData();
		if (clipboardData.length > 0 && Ametys.clipboard.Clipboard.getType() == Ametys.message.MessageTarget.CONTENT)
		{
			copiedContent = clipboardData[0];
		}
		
		this._contentIds = [];
		params['notsametype-contents'] = [];
		params['samecontent-contents'] = [];
		
		var description = '';
		
		if (copiedContent != null)
		{
            var allRightContents = params['allright-contents'];
            if (!this._checkSource(copiedContent, params))
            {
                this._updateTooltipDescription (description, params);
                this._contentIds = [];
                allRightContents = [];
            }
            else if (allRightContents.length > 0)
            {
                for (var i=0; i < allRightContents.length; i++)
                {
                    this._contentIds.push(allRightContents[i].id)
                }
                
                var me = this;
                Ext.Array.each(targets, function(target) {
                    
                    if (Ext.Array.contains (me._contentIds, target.getParameters().id))
                    {
                        if (!me._checkTarget(copiedContent, target, params))
                        {
                            // Remove content target from all rights contents
                            Ext.Array.remove(me._contentIds, target.getParameters().id);
                            me._removeFromAllRightContents (allRightContents, target.getParameters().id);
                        }
                    }
                });
                
                this._updateTooltipDescription (description, params);
            }
            else
            {
                description = this.getInitialConfig("error-description");
                this.setDescription (description);
            }
		}
		else
		{
			description = this.getInitialConfig("nocopiedcontent-description");
			this.setDescription (description);
		}
		
		this.setDisabled(this._contentIds.length == 0);
		this.toggle(this._contentIds.length > 0 && this.getInitialConfig()["enable-toggle"] == "true");
		
		this._workflowActionId = params['workflowaction-content-actionId'];
	},
    
    /**
     * Check if the copied content is a valid source
     * @param {Ametys.cms.content.Content} copiedContent The copied content
     * @param {Object} params the result
     * @return {Boolean} true if content can be copied
     */
    _checkSource: function(copiedContent, params)
    {
        return true;    
    },
    
    /**
     * Check if the copied content can be copied to the current target
     * @param {Ametys.cms.content.Content} copiedContent The copied content
     * @param {Ametys.message.MessageTarget} target the current targets
     * @param {Object} params the result
     * @return {Boolean} true if content can be copied
     */
    _checkTarget: function (copiedContent, target, params)
    {
        if (!Ext.Array.equals(copiedContent.getTypes(), target.getParameters().types) || !Ext.Array.equals(copiedContent.getMixins(), target.getParameters().mixins))
        {
            params['notsametype-contents'].push({
                id: target.getParameters().id,
                title: target.getParameters().title,
                description: "'" + target.getParameters().title + "'"
            });
            
            return false;
        }
        else if (copiedContent.getId() == target.getParameters().id)
        {
            params['samecontent-contents'].push({
                id: target.getParameters().id,
                title: target.getParameters().title,
                description: "'" + target.getParameters().title + "'"
            });
            
            return false;
        }
        
        return true;
    },
	
	/**
	 * Remove a content from "all-right" contents list
	 * @param {Object[]} allRightContents The all-right contents
	 * @param {String} id The id of the content to remove
	 * @private
	 */
	_removeFromAllRightContents: function (allRightContents, id)
	{
		var indexToRemove = -1;
		
		for (var i=0; i < allRightContents.length; i++)
		{
			if (allRightContents[i].id == id)
			{
				indexToRemove = i;
			}
		}
		
		Ext.Array.remove(allRightContents, allRightContents[indexToRemove]);
	},
	
	_updateTooltipDescription: function (description, params)
	{
		description = this._handlingMultiple (description, 'allright', params['allright-contents']);
        description = this._handlingMultiple(description, 'noread', params['noread-contents']);
		description = this._handlingMultiple(description, "locked", params['locked-contents']);
		description = this._handlingMultiple(description, "noright", params['noright-contents']);
		description = this._handlingMultiple(description, "notsametype", params['notsametype-contents']);
		description = this._handlingMultiple(description, "samecontent", params['samecontent-contents']);
		description = this._handlingMultiple(description, "nomodifiable", params['unmodifiable-contents']);
		description = this._handlingMultiple(description, "workflowaction", params['invalidworkflowaction-contents']);
		description = this._handlingMultiple(description, "workflowstep", params['invalidworkflowstep-contents']);
		
		this.setDescription (description);
        
        return description;
	}
});