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.AlternativeConditionalType;
import org.eclipse.cosmos.me.sdd.schema.ConditionalResourceConstraintType;

public class AlternativeConditionalCompare
{

	protected static Vector<AlternativeConditionalType> merge(List<AlternativeConditionalType> alternative, List<AlternativeConditionalType> alternative2)
	{
		Vector <AlternativeConditionalType> toRemove = new Vector <AlternativeConditionalType> ();
		Iterator <AlternativeConditionalType> iter1 = alternative.iterator();		
		//iterate through the items
		while (iter1.hasNext())
		{
			AlternativeConditionalType o1 = (AlternativeConditionalType) iter1.next();
			Iterator <AlternativeConditionalType> iter2 = alternative2.iterator();
			while (iter2.hasNext())
			{
				AlternativeConditionalType o2 = (AlternativeConditionalType) 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))
					{  
						//merge hosted resources, types and description groups
						toRemove.add(o2);
						o1.setDescription(DisplayTextCompare.merge(o1.getDescription(), o2.getDescription()));
						o1.setDisplayName(DisplayTextCompare.merge(o1.getDisplayName(), o2.getDisplayName()));
						o1.setShortDescription(DisplayTextCompare.merge(o1.getShortDescription(), o2.getShortDescription()));
						List<ConditionalResourceConstraintType> rcs = o1.getResourceConstraint();
						o1.getResourceConstraint().clear();
						o1.getResourceConstraint().addAll(ConditionalResourceConstraintCompare.merge(rcs,o2.getResourceConstraint()));
						
					}
				}
					
			}
		}
		
		alternative2.removeAll(toRemove);
		//remove all of the matches that were found
		
		Vector <AlternativeConditionalType> finals = new Vector <AlternativeConditionalType> ();
		//create and return a new collection with all of the remaining items
		finals.addAll(alternative);
		finals.addAll(alternative2);		
		
		return finals;
	}

	protected static boolean equals(AlternativeConditionalType o1, AlternativeConditionalType o2)
	{
		return (ConditionalResourceConstraintCompare.equals(o1.getResourceConstraint(),o2.getResourceConstraint()));
	}

}
