package org.eclipse.cosmos.me.sdd.tooling.btg.aggregator.comparisons;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.eclipse.cosmos.me.sdd.schema.ObjectFactory;
import org.eclipse.cosmos.me.sdd.schema.RelationshipConstraintType;
import org.eclipse.cosmos.me.sdd.schema.ResourceType;

public class RelationshipConstraintCompare
{

	protected static Vector<RelationshipConstraintType> merge(List<RelationshipConstraintType> rcs,	List<RelationshipConstraintType> rcs2)
	{
		Vector <RelationshipConstraintType> toRemove = new Vector <RelationshipConstraintType> ();
		Iterator <RelationshipConstraintType> iter1 = rcs.iterator();		
		//iterate through the items
		while (iter1.hasNext())
		{
			RelationshipConstraintType o1 = (RelationshipConstraintType) iter1.next();
			Iterator <RelationshipConstraintType> iter2 = rcs2.iterator();
			while (iter2.hasNext())
			{
				RelationshipConstraintType o2 = (RelationshipConstraintType) iter2.next();
				//if you find a match that hasn't been found, note it
				//one of the equals needs to be deleted with its children merged over
				if (toRemove.contains(o2)==false)
				{
					if (equals(o1, o2))
					{  
						toRemove.add(o2);
						o1 = merge(o1,o2);
					}
				}
					
			}
		}
		
		rcs2.removeAll(toRemove);
		//remove all of the matches that were found
		
		Vector <RelationshipConstraintType> finals = new Vector <RelationshipConstraintType> ();
		//create and return a new collection with all of the remaining items
		finals.addAll(rcs);
		finals.addAll(rcs2);		
		
		return finals;
	}
//	Type 	 Element 	 Attribute 	 Data Type 	 Compare?
//			<RelationshipConstraintType> 				
//					relatedResourceRef 	xsd:IDREF 	Yes
//					type 	xsd:QName 	Yes
//					any 	namespace="##other" 	 ?
//				DescriptionGroup 		DescriptionGroup 	Merge
//				Property 		<PropertyType> 	Yes 
	protected static RelationshipConstraintType merge(RelationshipConstraintType rc, RelationshipConstraintType rc2)
	{
		ObjectFactory objectFactory = new ObjectFactory();
		RelationshipConstraintType merged = objectFactory.createRelationshipConstraintType();
		
		merged.setRelatedResourceRef(rc.getRelatedResourceRef());
		merged.setType(rc.getType());
		merged.setDescription(DisplayTextCompare.merge(rc.getDescription(), rc2.getDescription()));
		merged.setShortDescription(DisplayTextCompare.merge(rc.getShortDescription(), rc2.getShortDescription()));
		merged.getProperty().addAll(rc.getProperty());
		
		return merged;
	}

	protected static boolean equals(RelationshipConstraintType rc, RelationshipConstraintType rc2)
	{
		if (!ResourceCompare.equals((ResourceType) rc.getRelatedResourceRef(), (ResourceType)rc2.getRelatedResourceRef()))
			return false;
		if (!StringCompare.equals(rc.getType(), rc2.getType()))
			return false;
		if (!PropertyCompare.equals(rc.getProperty(), rc2.getProperty()))
			return false;
		return true;
	}

}
