/*******************************************************************************
 * 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.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.DeploymentDescriptor;
import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.PackageDescriptor;
import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.SPISession;
import org.eclipse.cosmos.me.provisional.deployment.sdd.common.spi.artifact.AdditionalContent;
import org.eclipse.cosmos.me.provisional.deployment.sdd.tooling.btg.BTGProperty;
import org.eclipse.cosmos.me.provisional.deployment.sdd.tooling.btg.IBTGDataAggregator;
import org.eclipse.cosmos.me.provisional.deployment.sdd.tooling.btg.SDDFragment;
import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class Aggregator implements IBTGDataAggregator {
    Logger logger = Logger.getLogger("org.eclipse.cosmos.me.deployment.tooling.sdd.btg");//$NON-NLS-1$
    Logger consoleLogger = Logger.getLogger("org.eclipse.cosmos.me.deployment.tooling.sdd.btg.stdout");//$NON-NLS-1$
    static private DeploymentDescriptor dd1;
	static private DeploymentDescriptor dd2;
	
	static private PackageDescriptor pd1;
	static private PackageDescriptor pd2;
    
    
	public Collection<BTGProperty> getSupportedProperties() {
		List properties = new ArrayList();
		
				
		return properties;
	}

	
	public Collection<Document> aggregateSDDData(
			Collection<SDDFragment> fragments, Properties properties,
			boolean allowIncompleteSDDs) {
		
		try
		{	
			consoleLogger.info("welcome to the aggregator");
			
			if (fragments.size()!=0)
			{
				SPISession session = SPISession.DEFAULT_INSTANCE;			
				
				
				
				Iterator <SDDFragment> sddIter = fragments.iterator();
				DeploymentDescriptor resultingDD = (DeploymentDescriptor) session.buildDescriptorFromDocument((sddIter.next()).getFragment());
				while (sddIter.hasNext())
				{
					dd1 = resultingDD;
					dd2 = (DeploymentDescriptor) session.buildDescriptorFromDocument((sddIter.next()).getFragment());
					resultingDD = DeploymentDescriptorType.merge(resultingDD,dd2);
					
				}
				
				// Prepare the document for writing
				
				Document doc = (Document) resultingDD.getOwnerDocument();
				
				Collection<Document> returnArray = new ArrayList<Document>();
				returnArray.add(doc);
				//writeSDD(doc);
				
				return returnArray;
			}
			else
			{
				consoleLogger.info("No fragments passed to aggregator");
				return null;
			}

		}
		catch (Exception e)
		{ 
			e.printStackTrace();
			return null;
		}
				
	}
	
	public static void writeSDD(Document doc)
	{
		
		String outputLocation = "C:\\";
		try
		{
			//Comment out code to write out the xml
			DOMImplementationRegistry domRegistry = DOMImplementationRegistry.newInstance();
			DOMImplementationLS domImpl = (DOMImplementationLS) domRegistry.getDOMImplementation("LS");
			LSSerializer serializer = domImpl.createLSSerializer();
			serializer.getDomConfig().setParameter("format-pretty-print", true);
			DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation();
		
			LSOutput output = impl.createLSOutput();
			
			BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputLocation+"outputSDD.xml"));
	        
	        //Start writing to the output stream
	        
			output.setCharacterStream(bufferedWriter);
			serializer.write(doc, output);
		
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
	}
	
	public static DeploymentDescriptor getDd1()
	{
		return dd1;
	}
	
	public static DeploymentDescriptor getDd2()
	{
		return dd2;
	}
	
	public static boolean setDd1(DeploymentDescriptor dd)
	{
		try
		{
			dd1 = dd;
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}
	
	public static boolean setDd2(DeploymentDescriptor dd)
	{
		try
		{
			dd2 = dd;
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}
	
	public static Collection<DeploymentDescriptor> getAllDeploymentDescriptors()
	{
		Collection<DeploymentDescriptor> deploymentDescriptors = new ArrayList<DeploymentDescriptor>();
		deploymentDescriptors.add(getDd1());
		deploymentDescriptors.add(getDd2());
		
		return deploymentDescriptors;
		
	}
	
	public static PackageDescriptor getPd1()
	{
		return pd1;
	}
	
	public static PackageDescriptor getPd2()
	{
		return pd2;
	}
	
	public static boolean setPd1(PackageDescriptor pd)
	{
		try
		{
			pd1 = pd;
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}
	
	public static boolean setPd2(PackageDescriptor pd)
	{
		try
		{
			pd2 = pd;
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}
	
	public static Collection<PackageDescriptor> getAllPackageDescriptors()
	{
		Collection<PackageDescriptor> packageDescriptors = new ArrayList<PackageDescriptor>();
		packageDescriptors.add(getPd1());
		packageDescriptors.add(getPd2());
		
		return packageDescriptors;
		
	}
}




