package org.eclipse.cosmos.me.provisional.deployment.sdd.tooling.btg.aggregator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.contentunit.Relationship;

public class RelationshipType {
	
	/*
	 * <RelationshipType> 	 	 	 	
		relatedResourceRef 	xsd:IDREF 	Yes
		type 	xsd:QName 	Yes
		any 	namespace="##other" 	 ?
		Property 		<PropertyType> 	Yes
		any 		namespace="##other" 	 ? 
	 */

	public static Collection<Relationship> merge(Collection<Relationship> relationships1, Collection<Relationship> relationships2)
	{
		Iterator <Relationship> r1Iter = relationships1.iterator();
		ArrayList <Relationship> rShipsToRemove = new ArrayList <Relationship> ();
		
		while (r1Iter.hasNext())
		{
			Relationship r1 = r1Iter.next();
			Iterator <Relationship> r2Iter = relationships2.iterator();
			while (r2Iter.hasNext())
			{
				Relationship r2 = r2Iter.next();
				if (equals(r1,r2))
				{
					rShipsToRemove.add(r2);
				}
			}
		}
		
		relationships1.addAll(relationships2);
		relationships1.removeAll(rShipsToRemove);
				
		return relationships1;
	}
	
	public static boolean equals(Relationship relationship1, Relationship relationship2)
	{
		if (!ResourceType.equals(Util.resolveResourceRef(relationship1.getRelatedResourceReference()), Util.resolveResourceRef(relationship2.getRelatedResourceReference())))
			return false;
		if (!StringType.equals(relationship1.getType(), relationship2.getType()))
			return false;
		if (!PropertyType.equals(relationship1.getProperties(), relationship2.getProperties()))
			return false;
		
		return true;
	}

}
