/*
 *  Copyright 2014 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 is a relation handler between:
 * * source : a page
 * * destination : a page or sitemap root
 * 
 * @private
 */
Ext.define('Ametys.plugins.web.page.relations.PagesRelationHandler', {
	extend: 'Ametys.relation.RelationHandler',
	
	/** 
	 * @protected
	 * @property {RegExp} sourceTargetType The message target type of the source to handle
	 */
	sourceTargetType: /^page$/,
	
	/**
	 * @protected
	 * @property {RegExp} destTargetType The message target type of the target to handle
	 */
	destTargetType: /^(page|sitemap)$/,
	
	supportedRelations: function(source, target)
	{
		return this._supportedRelations(source.targets, target.targets);
	},
	
	/**
	 * @protected
	 * Do the #supportedRelations work but based only on targets array
	 * This method return the list of supported operations between the source and the target points of a relation.
	 * The implementation should only cares about targets and does not have to check upon source and target relations: a later filter is done by the Ametys.relation.RelationManager.
	 * @param {Object/Object[]/Ametys.message.MessageTarget/Ametys.message.MessageTarget[]} sourceTargets The source point of the relation operation. Targets are assumed to be ready.
	 * @param {Object/Object[]/Ametys.message.MessageTarget/Ametys.message.MessageTarget[]} targetTargets The end point of the relation operation. Targets are assumed to be ready.
	 * @return {Ametys.relation.Relation/Ametys.relation.Relation[]} Returns the supported operations between those two points. The order is important: after filtering that array, the first relation is considered as the default one.
	 */
	_supportedRelations: function(sourceTargets, targetTargets)
	{
		sourceTargets = Ext.Array.from(sourceTargets);
		targetTargets = Ext.Array.from(targetTargets);
		
		var sourceMatch = Ametys.message.MessageTargetHelper.findTargets(sourceTargets, this.sourceTargetType, 1);
		if (sourceMatch.length == 0 || sourceMatch.length != sourceTargets.length)
		{
			// Source is not made of only pages or is empty.
			return [];
		}
		
		var targetMatch = Ametys.message.MessageTargetHelper.findTargets(targetTargets, this.destTargetType, 1);
		if (targetMatch.length != 1 || targetTargets.length != 1)
		{
			// Target should be a single page or the sitemap root
			return [];
		}
        
        var targetId;
        if (targetMatch[0].isMessageTarget)
        {
            targetId = targetMatch[0].getParameters()['id'];
        }
        else
        {
            targetId = targetMatch[0].parameters['id'];
        }
        
		var canRemoveFromSource = true;
		for (var i = 0; i < sourceMatch.length; i++)
		{
			// Getting sourceId and rights from either an object or a MessageTarget
			var sourceId, rights, parentId;
			if (sourceMatch[i].isMessageTarget)
			{
				sourceId = sourceMatch[i].getId();
				rights = sourceMatch[i].getParameters()['rights'];
                parentId = sourceMatch[i].getParameters()['parentId'];
			}
			else
			{
				sourceId = sourceMatch[i].id;
				rights = sourceMatch[i].parameters['rights'];
                parentId = sourceMatch[i].parameters['parentId'];
			}
			
			if (rights
				&& !Ext.Array.contains(rights, "Web_Rights_Page_Delete")
                && targetId != parentId) // check delete right only if it is not a reorder
			{
				canRemoveFromSource = false;
			}
		}
		
		// Getting rights from either an object or a MessageTarget
		var rights;
		if (targetMatch[0].isMessageTarget)
		{
			rights = targetMatch[0].getParameters()['rights'];
		}
		else
		{
			rights = targetMatch[0].parameters['rights'];
		}
		
		var canAdd = !rights || Ext.Array.contains(rights, "Web_Rights_Page_Create")
		if (!canAdd)
		{
			// No right to create new page under target page or sitemap.
			return [];
		}
			
		var relations = [];
		
		if (canRemoveFromSource)
		{
			relations.push(Ext.create('Ametys.relation.Relation', {
				type: Ametys.relation.Relation.MOVE,
				label: "{{i18n PLUGINS_WEB_RELATIONS_DEFAULTPAGE_LABEL}}",
				description: "{{i18n PLUGINS_WEB_RELATIONS_DEFAULTPAGE_DESCRIPTION}}",
				smallIcon: null,
				mediumIcon: null,
				largeIcon: null
			}));
		}
			
		return relations;
	},
	
	link: function(source, target, callback, relationType)
	{
		this._link(source.getTargets(), target.getTarget(), target.positionInTargets, callback, relationType);
	},
	
	/**
	 * @protected
	 * Do the #link work but based only on targets array
	 * The method is called to link source to target using the given relation. 
	 * This operation can be asynchronous and will call callback at the end.
	 * In most cases this implementation will send a Ametys.message.Message to inform the UI that the operation was done.
	 * @param {Ametys.message.MessageTarget[]} sourceTargets The source point of the link operation. Targets are assumed to be ready.
	 * @param {Ametys.message.MessageTarget} target The end point of the link operation. Targets are assumed to be ready.
	 * @param {Number} index The insert position in child nodes. -1 means as last child.
	 * @param {Function} callback The callback to call when operation has ended. 
	 * @param {boolean} callback.sucess True if the operation was successful
	 * @param {String} relationType The relation to create. One of the constants Ametys.relation.Relation.MOVE, Ametys.relation.Relation.COPY or Ametys.relation.Relation.REFERENCE.
	 */
	_link: function(sourceTargets, target, index, callback, relationType)
	{
		var me = this;
		Ext.Array.forEach(Ametys.message.MessageTargetHelper.findTargets(sourceTargets, this.sourceTargetType, 1), function(sourceTarget) {
			
			Ametys.web.page.PageDAO.movePage (
					[sourceTarget.getParameters().id, target.getParameters().id, index],
					me._linkCb,
					{scope: this, arguments: [callback]}
			);
		});
	},
	
	/**
	 * @private
	 * Callback of the link operation. That will call the initial callback.
	 * @param {Object} response The server response
	 * @param {Object[]} args the callback arguments
	 */
	_linkCb: function(response, args)
	{
		args[0](response.id != null);
	}
});