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.VersionRangeType;

public class VersionRangeCompare
{

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

//	<VersionRangeType> 	 	 	 	
//	MinVersion 		<VersionType> 	Yes
//	MaxVersion 		<MaxVersionType> 	Yes
//	FixName 		xsd:string 	 ? 
	protected static VersionRangeType merge(VersionRangeType o1,	VersionRangeType o2)
	{
		ObjectFactory objectFactory = new ObjectFactory();
		VersionRangeType vr = objectFactory.createVersionRangeType();
		vr.getFixName().addAll(o1.getFixName());
		vr.getFixName().addAll(o2.getFixName());
		vr.setMaxVersion(o1.getMaxVersion());
		vr.setMinVersion(o1.getMinVersion());
		return vr;
	}

	protected static boolean equals(VersionRangeType vr, VersionRangeType vr2)
	{
		if (MaxVersionCompare.equals(vr.getMaxVersion(),vr2.getMaxVersion()))
			return false;
		if (StringCompare.equals(vr.getMinVersion(),vr2.getMinVersion()))
			return false;
		return true;
	}
}
