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


public class ContentsType {
	
	public static Collection<PackageContent> merge(Collection<PackageContent> packageContents1, Collection<PackageContent> packageContents2)
	{
		
		Collection <PackageContent> packageContentsToRemove = new ArrayList <PackageContent> ();
		Iterator <PackageContent> packageContentIter1 = packageContents1.iterator();		
		//iterate through the packageContents
		while (packageContentIter1.hasNext())
		{
			PackageContent packageContent1 = (PackageContent) packageContentIter1.next();
			Iterator <PackageContent> packageContentIter2 = packageContents2.iterator();
			while (packageContentIter2.hasNext())
			{
				PackageContent packageContent2 = (PackageContent) packageContentIter2.next();
				//if you find a match that hasn't been found, note it
				//one of the equals needs to be deleted with its children merged over
				if (packageContentsToRemove.contains(packageContent2)==false)
				{
					if (ContentType.equals(packageContent1, packageContent2))
					{  //merge hosted packageContents, types and description groups
						packageContentsToRemove.add(packageContent2);						
						packageContent1 = ContentType.merge(packageContent1,packageContent2);
						
					}
				}
					
			}
		}
		
		packageContents2.removeAll(packageContentsToRemove);
		//remove all of the matches that were found
		
		Collection <PackageContent> finalPackageContents = new ArrayList <PackageContent> ();
		//create and return a new collection with all of the remaining items
		finalPackageContents.addAll(packageContents1);
		finalPackageContents.addAll(packageContents2);		
		
		return finalPackageContents;
	}		

}
