/*
 *  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 controller controls move operations to perform on links
 */
Ext.define('Ametys.plugins.linkdirectory.link.MoveLinkController', {
	extend: 'Ametys.ribbon.element.ui.ButtonController',
	
	/**
	 * @cfg {String} role the role of the button. Can be "move-first", "move-up", "move-down" or "move-last".
	 */
	
	constructor: function(config)
	{
		this.callParent(arguments);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.MOVED, this._onMoved, this);
	},
	
	/**
	 * @private
	 * Listener when a move occurs on a link
	 * Will update the state of the buttons effectively upon the current selection.
	 * @param {Ametys.message.Message} message The moved message.
	 */
	_onMoved: function (message)
	{
		if (this.updateTargetsInCurrentSelectionTargets(message))
        {
            this.refresh();
        }
	},
	
	updateState: function()
	{
		this._getStatus(this.getMatchingTargets());
	},
	
	areSameTargets: function(target1, target2)
	{
		var match = this.callParent(arguments);
		if (match && target1.getParameters().id != null && target2.getParameters().id != null)
		{
			return target1.getParameters().id == target2.getParameters().id;
		}
		else
		{
			return match;
		}
	},
	
	/**
	 * @private
	 * Get the status of the selected link targets
	 * @param targets The link targets
	 */
	_getStatus: function (targets)
	{
		targets.length == 1 && this._testLink(targets[0]) ? this.enable() : this.disable(); 
	},
	
	/**
	 * @private
	 * Test link position
	 * @return {Ametys.message.MessageTarget} The link target to check
	 */
	_testLink: function(target)
	{
		var role = this.role,
	        index = target.getParameters().position,
	        size= target.getParameters().count;
	        
	    return (((role == 'move-up' || role == 'move-first') && index != 0) || ((role == 'move-down' || role == 'move-last') && index != size - 1)) ? true : false;
	}
});