/*******************************************************************************
 * Copyright (c) 2008 SAS Institute Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     SAS Institute Inc. - initial API and implementation
 ******************************************************************************/
package org.eclipse.cosmos.me.provisional.deployment.sdd.tooling.btg.aggregator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;

import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.contentunit.ResultingChange;
import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.contentunit.ResultingResource;


public class ResultingChangeType {
	
	/*
	 * <ResultingChangeType> 	 	 	 	
		resourceRef 	xsd:IDREF 	Yes
		any 	namespace="##other" 	 ?
		DescriptionGroup 		DescriptionGroup 	Merge
		Condition 		<ConditionType> 	Yes
		Name 		<VariableExpressionType> 	Merge
		Property 		<ResultingPropertyType> 	Merge
		Relationship 		<RelationshipType> 	Merge
		any 		namespace="##other" 	 ? 
	 */
	
	public static boolean equals(ResultingChange change1, ResultingChange change2)
	{
		
		//TODO: SPI Doesn't let you get resourceRef out???????????
		
		if ((change1.getCondition()==null)&&(change2.getCondition()!=null))
			return false;
		if ((change1.getCondition()!=null)&&(change2.getCondition()==null))
			return false;
		if ((change1.getCondition()!=null)&&(change2.getCondition()!=null))
		{
			if (!ConditionType.equals(change1.getCondition(), change2.getCondition()))
				return false;
		}		
		return true;		
	}
	
	public static ResultingChange merge(ResultingChange change1, ResultingChange change2)
	{
		Properties myProps = change1.getProperties();
		myProps.putAll(change2.getProperties());
		change1.setProperties(myProps);		
		
		if (equals(change1,change2))
		{
			change1.setDescription(TranslatableStringType.merge(change1.getDescription(),change2.getDescription()));
			change1.setName(StringType.merge(change1.getName(), change2.getName()));
			change1.setRelationships(RelationshipType.merge(change1.getRelationships(),change2.getRelationships()));
			return change1;
		}
		else return null;
	}

	public static boolean equals(Collection <ResultingChange> changes1, Collection <ResultingChange> changes2)
	{		
		Iterator <ResultingChange> iter1 = changes1.iterator();
		
		while (iter1.hasNext())
		{
			ResultingChange change1 = iter1.next();
			boolean match = false;
			Iterator <ResultingChange> iter2 = changes2.iterator();
			
			while ((iter2.hasNext())||(!match))
			{
				ResultingChange change2 = iter2.next();
				if (equals(change1,change2))
				{
					match = true;
				}
			}
			if (!match)
				return false;			
		}
			
		return true;
	}

}
