/*******************************************************************************
 * 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.Collection;
import java.util.Iterator;
import java.util.Set;

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 void merge(Collection<Completion> newVars, Set<Completion> mergedVars)
	{
		for(Iterator<Completion> i = newVars.iterator(); i.hasNext();) {
			boolean matches = false;
			Completion newVar = i.next();
			
			for(Iterator<Completion> i2 = mergedVars.iterator(); i2.hasNext();) {
				Completion mergedVar = i2.next();
				
				if(equals(newVar, mergedVar)) {
					matches = true;
					merge(newVar, mergedVar);
					break;
				}					
			}
			
			if(!matches) {
				mergedVars.add(newVar);
			}
		}
	}

	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;
	}

	static Completion merge(Completion newCompletion, Completion merged)
	{
		merged.setDescription(TranslatableStringType.merge(newCompletion.getDescription(), merged.getDescription()));
		merged.setShortDescription(TranslatableStringType.merge(newCompletion.getShortDescription(), merged.getShortDescription()));
		// TODO: merge condition.  Not sure how.
		
		return merged;
	}

}