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

public class ResourcePropertyCompare
{

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

	private static boolean equals(ResourcePropertyType o1, ResourcePropertyType o2)
	{
		if (o1.isSensitive()!=o2.isSensitive())
			return false;
		if (!ResourceCompare.equals((ResourceType)o1.getResourceRef(), (ResourceType)o1.getResourceRef()))
			return false;
		if (!StringCompare.equals(o1.getPropertyName(), o2.getPropertyName()))
			return false;
		return true;
	}
	protected static ResourcePropertyType merge(ResourcePropertyType o1, ResourcePropertyType o2)
	{
		ObjectFactory objectFactory = new ObjectFactory();
		ResourcePropertyType merged = objectFactory.createResourcePropertyType();
				
		merged.setShortDescription(DisplayTextCompare.merge(o1.getShortDescription(), o2.getShortDescription()));
		merged.setDescription(DisplayTextCompare.merge(o1.getDescription(), o2.getDescription()));
		
		return merged;
	}	


}
