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

public class DerivedVariableCompare
{

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

	private static boolean equals(DerivedVariableType o1, DerivedVariableType o2)
	{
		if (o1.isSensitive()!=o2.isSensitive())
			return false;
		if (!StringCompare.equals(o1.getExpression(),o2.getExpression()))
			return false;
		return true;
	}
	protected static DerivedVariableType merge(DerivedVariableType o1, DerivedVariableType o2)
	{
		ObjectFactory objectFactory = new ObjectFactory();
		DerivedVariableType merged = objectFactory.createDerivedVariableType();
				
		merged.setShortDescription(DisplayTextCompare.merge(o1.getShortDescription(), o2.getShortDescription()));
		merged.setDescription(DisplayTextCompare.merge(o1.getDescription(), o2.getDescription()));
		
		merged.getConditionalExpression().addAll(ConditionalDerivedVariableExpressionCompare.merge(o1.getConditionalExpression(),o2.getConditionalExpression()));
		
		return merged;
	}	

}
