/*******************************************************************************
 * 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.variable.BaseVariable;
import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.variable.DerivedVariable;
import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.variable.ResourceProperty;

public class BaseVariableType
{
	static <T extends BaseVariable> void merge(Collection<T> newVars, Set<T> mergedVars)
	{
		for(Iterator<T> i = newVars.iterator(); i.hasNext();) {
			boolean matches = false;
			T newVar = i.next();
			
			for(Iterator<T> i2 = mergedVars.iterator(); i2.hasNext();) {
				T mergedVar = i2.next();
				
				if(equals(newVar, mergedVar)) {
					matches = true;
					merge(newVar, mergedVar);
					break;
				}					
			}
			
			if(!matches) {
				mergedVars.add(newVar);
			}
		}
	}

	static boolean equals(BaseVariable b1, BaseVariable b2)
	{
		boolean equals = true;
		
		// handle the BaseVariable values
		equals = equals && BooleanType.equals(b1.isSensitive(), b2.isSensitive());
		
		if(b1 instanceof DerivedVariable) {
			equals = equals && DerivedVariableType.equals((DerivedVariable)b1, (DerivedVariable)b2);
		}
		else if(b1 instanceof ResourceProperty) {
			equals = equals && ResourcePropertyType.equals((ResourceProperty)b1, (ResourceProperty)b2);
		}
				
		return equals;
	}

	static BaseVariable merge(BaseVariable newParm, BaseVariable merged)
	{
		merged.setDescription(TranslatableStringType.merge(newParm.getDescription(), merged.getDescription()));
		merged.setShortDescription(TranslatableStringType.merge(newParm.getShortDescription(), merged.getShortDescription()));
		
		return merged;
	}

}