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

import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.variable.StringParameter;

public class StringParameterType
{	
	static StringParameter merge(StringParameter newParm, StringParameter merged)
	{	
		BigInteger finalMinLength = newParm.getMinLength();
		BigInteger finalMaxLength = newParm.getMaxLength();
		
		//if stringParameter2 has greater min length, use 
		if( newParm.getMinLength().compareTo(merged.getMinLength()) < 0 ){
			finalMinLength = merged.getMinLength();
		}
		
		//if stringParameter2 has lower max length, use
		if( newParm.getMaxLength().compareTo(merged.getMaxLength()) > 0 ){
			finalMaxLength = merged.getMaxLength();
		}
		
		if( finalMinLength.compareTo(finalMaxLength) > 0 ){
			//TODO: Throw Error
		}
		else{
			//merge
			merged.setMinLength(finalMinLength);
			merged.setMaxLength(finalMaxLength);
		}
		
		//merge cases
		String finalCase = StringCaseType.merge(newParm.getCase(), merged.getCase());
		merged.setCase(finalCase);
		
		
		//merge valid values
		Collection<String> finalValidValues = new ArrayList<String>();
		Collection<String> nonDuplicates = new ArrayList<String>();
		
		Iterator<String> it1 = newParm.getValidValues().iterator();
		
		while( it1.hasNext() ){
			String value1 = it1.next();
			Iterator<String> it2 = merged.getValidValues().iterator();
			
			while( it2.hasNext() ){
				String value2 = it2.next();
				if( !value2.equalsIgnoreCase(value1) ){
					nonDuplicates.add(value2);
				}
			}
			
		}
		
		finalValidValues.addAll(newParm.getValidValues());
		finalValidValues.addAll(nonDuplicates);
		
		merged.setValidValues(finalValidValues);
		
		return merged;
	}	
}
