/*******************************************************************************
 * 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.PackageContent;


public class ContentsType {
	
	public static Collection<PackageContent> merge(Collection<PackageContent> contents1, Collection<PackageContent> contents2){
		
		Iterator<PackageContent> contents1Iterator = contents1.iterator();
		Collection<PackageContent> mergedContents1 = new ArrayList<PackageContent>();
		Collection<PackageContent> mergedContents2 = new ArrayList<PackageContent>();
		Collection<PackageContent> mergedNew = new ArrayList<PackageContent>();
		
		//check whether each content in contents one is equal/mergable with content in contents2
		while( contents1Iterator.hasNext()){
			PackageContent content1 = contents1Iterator.next();
			
			Iterator<PackageContent> contents2Iterator = contents2.iterator();
			
			while( contents2Iterator.hasNext()){
				PackageContent content2 = contents2Iterator.next();
				
				if( ContentType.equals(content1,content2) ){
					//content can be merged, merge and add old contents to merged list
					PackageContent newContent = ContentType.merge(content1, content2);
					
					mergedNew.add(newContent);
					mergedContents1.add(content1);
					mergedContents2.add(content2);
				}
			}					
		}
		
		//remove all entries that where merged
		contents1.removeAll(mergedContents1);
		contents2.removeAll(mergedContents2);
		
		//add merged and remaining non-merged contents together
		Collection<PackageContent> finalContents = new ArrayList<PackageContent>();
		finalContents.addAll(contents1);
		finalContents.addAll(contents2);
		finalContents.addAll(mergedNew);
		
		return finalContents;
	}

}
