/*******************************************************************************
 * 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 org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.Resource;
import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.contentunit.Completion;

public class CompletionType
{
	static Collection <Completion> merge(Collection<Completion> completion1, Collection<Completion> completion2)
	{
		/*
		<CompletionType> 	 	 	 	
		type 	<CompletionTypeNamesType> 	Yes
		resourceRef 	xsd:IDREF 	Yes
		operation 	<OperationListType> 	Yes
		any 	namespace="##other" 	 ?
		DisplayElementGroup 		<DisplayElementGroup> 	Merge
		Condition 		<ConditionType> 	Merge
		any 		namespace="##other" 	 ?	*/
		
		Collection <Completion> completionsToRemove = new ArrayList();
				
		Iterator compIter1 = completion1.iterator();		
		
		while (compIter1.hasNext())
		{
			Completion comp1 = (Completion) compIter1.next();
			Iterator compIter2 = completion2.iterator();
			while (compIter2.hasNext())
			{
				Completion comp2 = (Completion) compIter2.next();
				
				if (equals(comp1, comp2))
				{
					completionsToRemove.add(comp2);
				}
					
			}
		}
		
		completion2.removeAll(completionsToRemove);
		
		Collection <Completion> finalComps = new ArrayList();
		finalComps.addAll(completion1);
		finalComps.addAll(completion2);		
		
		return finalComps;
		
		
	}

	static boolean equals(Completion c1, Completion c2)
	{
		boolean equals = true;

		equals = equals && StringType.equals(c1.getCompletionType(), c2.getCompletionType());
		equals = equals && OperationsType.equals(c1.getCompletionOperations(), c2.getCompletionOperations());
		
		Resource rc1 = Util.resolveResourceRef(c1.getCompletionResourceReference());
		Resource rc2 = Util.resolveResourceRef(c2.getCompletionResourceReference());

		equals = equals && ResourceType.equals(rc1, rc2);		
				
		return equals;
	}
	
}