package org.eclipse.cosmos.me.sdd.tooling.btg.aggregator.comparisons;

import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import org.eclipse.cosmos.me.sdd.schema.ResourceType;

public class ResourceCompare {
	
	protected static Collection <ResourceType> merge(Collection <ResourceType> resources1, Collection <ResourceType> resources2)
	{		
		Collection <ResourceType> resourcesToRemove = new Vector <ResourceType> ();
		Iterator <ResourceType> resourceIter1 = resources1.iterator();		
		//iterate through the resources
		while (resourceIter1.hasNext())
		{
			ResourceType resource1 = (ResourceType) resourceIter1.next();
			Iterator <ResourceType> resourceIter2 = resources2.iterator();
			while (resourceIter2.hasNext())
			{
				ResourceType resource2 = (ResourceType) resourceIter2.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 (resourcesToRemove.contains(resource2)==false)
				{
					if (equals(resource1, resource2))
					{  
						//merge hosted resources, types and description groups
						resourcesToRemove.add(resource2);						
						resource1.getHostedResource().addAll(merge(resource1.getHostedResource(),resource2.getHostedResource()));
						
					}
				}
					
			}
		}
		
		resources2.removeAll(resourcesToRemove);
		//remove all of the matches that were found
		
		Vector <ResourceType> finalResources = new Vector <ResourceType> ();
		//create and return a new collection with all of the remaining items
		finalResources.addAll(resources1);
		finalResources.addAll(resources2);		
		
		return finalResources;
		
	}	
	
	protected static boolean equals(ResourceType resource1, ResourceType resource2)
	{	
		
		
		try
		{
			if (StringCompare.equals(resource1.getType(), resource2.getType())==false)
				return false;
		}
		catch (NullPointerException e)
		{
			System.out.println("Required parameter \"Type\" missing from resource");
			return false;
		}
		
		if ((resource1.getProperty()!=null)&&(resource2.getProperty()==null))
			return false;
		if ((resource1.getProperty()==null)&&(resource2.getProperty()!=null))
			return false;
		if ((resource1.getProperty()!=null)&&(resource2.getProperty()!=null))		
			if (PropertyCompare.equals(resource1.getProperty(), resource2.getProperty())==false)		
				return false;
		if ((resource1.getName()!=null)&&(resource2.getName()==null))
			return false;
		if ((resource1.getName()==null)&&(resource2.getName()!=null))
			return false;
		if ((resource1.getName()!=null)&&(resource2.getName()!=null))		
			if (StringCompare.equals(resource1.getName(), resource2.getName())==false)
				return false;
		
		return true;
	}

}
