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

import java.util.Collection;
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.ResourceType;
import org.eclipse.cosmos.me.sdd.schema.UniquenessConstraintType;

public class UniquenessConstraintCompare
{

	public static Collection<UniquenessConstraintType> merge(List<UniquenessConstraintType> uc,	List<UniquenessConstraintType> uc2)
	{
		Vector <UniquenessConstraintType> toRemove = new Vector <UniquenessConstraintType> ();
		Iterator <UniquenessConstraintType> iter1 = uc.iterator();		
		//iterate through the items
		while (iter1.hasNext())
		{
			UniquenessConstraintType o1 = (UniquenessConstraintType) iter1.next();
			Iterator <UniquenessConstraintType> iter2 = uc2.iterator();
			while (iter2.hasNext())
			{
				UniquenessConstraintType o2 = (UniquenessConstraintType) 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);
					}
				}
					
			}
		}
		
		uc2.removeAll(toRemove);
		//remove all of the matches that were found
		
		Vector <UniquenessConstraintType> finals = new Vector <UniquenessConstraintType> ();
		//create and return a new collection with all of the remaining items
		finals.addAll(uc);
		finals.addAll(uc2);		
		
		return finals;
	}

//	 distinctResourceRef 	 xsd:IDREF 	 Yes
//		DescriptionGroup 		DescriptionGroup 	Merge 
	protected static UniquenessConstraintType merge(UniquenessConstraintType o1,	UniquenessConstraintType o2)
	{
		ObjectFactory objectFactory = new ObjectFactory();
		UniquenessConstraintType uc = objectFactory.createUniquenessConstraintType();
		uc.setDescription(DisplayTextCompare.merge(o1.getDescription(), o2.getDescription()));
		uc.setShortDescription(DisplayTextCompare.merge(o1.getShortDescription(), o2.getShortDescription()));
		uc.setDistinctResourceRef(o1.getDistinctResourceRef());
		return uc;
	}

	protected static boolean equals(UniquenessConstraintType rc, UniquenessConstraintType rc2)
	{
		if (!ResourceCompare.equals((ResourceType)rc.getDistinctResourceRef(),(ResourceType)rc2.getDistinctResourceRef()))
			return false;
		return true;
	}

}
