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.CompletionType;
import org.eclipse.cosmos.me.sdd.schema.ObjectFactory;
import org.eclipse.cosmos.me.sdd.schema.ResourceType;

public class CompletionCompare
{

	protected static Collection<CompletionType> merge(List<CompletionType> c, List<CompletionType> c2)
	{
		Vector <CompletionType> toRemove = new Vector <CompletionType> ();
		Iterator <CompletionType> iter1 = c.iterator();		
		//iterate through the items
		while (iter1.hasNext())
		{
			CompletionType o1 = (CompletionType) iter1.next();
			Iterator <CompletionType> iter2 = c2.iterator();
			while (iter2.hasNext())
			{
				CompletionType o2 = (CompletionType) 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);
					}
				}
					
			}
		}
		
		c2.removeAll(toRemove);
		//remove all of the matches that were found
		
		Vector <CompletionType> finals = new Vector <CompletionType> ();
		//create and return a new collection with all of the remaining items
		finals.addAll(c);
		finals.addAll(c2);		
		
		return finals;
	}
	
//	<CompletionType> 	 	 	 	
//	type 	<CompletionTypeNamesType> 	Yes
//	resourceRef 	xsd:IDREF 	Yes
//	operation 	<OperationListType> 	Yes
//	any 	namespace="##other" 	 ?
//DisplayElementGroup 		<DisplayElementGroup> 	Merge
//Condition 		<ConditionType> 	Merge
//any 		namespace="##other" 	 ? 

	protected static CompletionType merge(CompletionType o1,	CompletionType o2)
	{
		ObjectFactory objectFactory = new ObjectFactory();
		CompletionType merged = objectFactory.createCompletionType();
		merged.setDescription(DisplayTextCompare.merge(o1.getDescription(), o2.getDescription()));
		merged.setDisplayName(DisplayTextCompare.merge(o1.getDisplayName(), o2.getDisplayName()));
		merged.setShortDescription(DisplayTextCompare.merge(o1.getShortDescription(), o2.getShortDescription()));
		merged.setType(o1.getType());
		merged.setResourceRef(o1.getResourceRef());
		merged.getOperation().addAll(o1.getOperation());
		merged.setCondition(ConditionCompare.merge(o1.getCondition(), o2.getCondition()));
		return merged;
	}

	protected static boolean equals(CompletionType c, CompletionType c2)
	{
		if (!StringCompare.equals(c.getType(),c2.getType()))
			return false;
		if (!ResourceCompare.equals((ResourceType)c.getResourceRef(), (ResourceType)c2.getResourceRef()))
			return false;
		if (!OperationCompare.equals(c.getOperation(), c2.getOperation()))
			return false;
		return true;
	}

}