/*
 *  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 : explorer node or explorer resource
 * * destination : explorer node
 * 
 * E.g. when you drag an explorer file to an explorer folder
 * @private
 */
Ext.define('Ametys.plugins.cms.relations.DefaultContentAttachmentsRelationHandler', {
	extend: 'Ametys.plugins.explorer.relations.ExplorerResourcesRelationHandler',
	
	/**
	 * @private
	 * Get the sub targets of the content target
	 * @param {Ametys.relation.RelationPoint} relationPoint The relation point to check
	 * @return {Ametys.message.MessageTarget[]} The message targets under the root single content target. Can be null if the root is not single or is not a content
	 */
	_getContentSubTarget: function(relationPoint)
	{
		var contentMatch = Ametys.message.MessageTargetHelper.findTargets(relationPoint.targets, /^content$/, 1);
		if (contentMatch.length != 1 || contentMatch.length != relationPoint.targets.length)
		{
			// Should be a single content
			return null;
		}
		return contentMatch[0].subtargets;
	},
	
	supportedRelations: function(source, target)
	{
		var sourceContentMatch = this._getContentSubTarget(source);
		var targetContentMatch = this._getContentSubTarget(target);
		if (sourceContentMatch == null || targetContentMatch == null)
		{
			return [];
		}
		
		return this._supportedRelations(sourceContentMatch, targetContentMatch);
	},
	
	link: function(source, target, callback, relationType)
	{
		var sourceContentMatch = this._getContentSubTarget(source);
		var targetContentMatch = this._getContentSubTarget(target);
		
		this._link(sourceContentMatch, targetContentMatch[0], callback, relationType);
	}
});