/*
 * This file has been developed at the University of Munich, Chair for Programming & Software Engineering.
 * 
 * This file is licensed under the Eclipse Public License (EPL) 1.0
 * 
 */
package eu.mdd4soa.trans.smm2bpel;

import org.eclipse.core.resources.IFile;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.Resource.Factory.Registry;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMLContentHandlerImpl;
import org.eclipse.emf.ecore.xmi.impl.XMLResourceFactoryImpl;

import eu.mdd4soa.smm.exception.InvalidSetupException;
import eu.mdd4soa.smm.statik.Participant;

public class EMFUtil {

	public static Participant loadParticipant(IFile file) throws InvalidSetupException {


		if (file == null)
			throw new InvalidSetupException("File is null.");

		if (!file.exists())
			throw new InvalidSetupException("File does not exist: " + file.getFullPath().toOSString());

		ResourceSet resourceSet= new ResourceSetImpl();

		addHeadlessInformation(resourceSet);

		Resource resource= resourceSet.getResource(URI.createFileURI( ((IFile) file).getLocation().toString()), true);

		EList<EObject> contents= resource.getContents();
		if (contents == null || contents.size() == 0)
			throw new InvalidSetupException("Could not read EMF model from input file.");

		EObject object= resource.getContents().get(0);

		if (! (object instanceof Participant))
			throw new InvalidSetupException("Input EMF file does not contain a UML model; class was " + object.getClass());

		return (Participant) object;

	}

	private static void addHeadlessInformation(ResourceSet resourceSet) {

		// Headless?
		if (SMM2BPELPlugin.getDefault() == null || SMM2BPELPlugin.getDefault().getBundle() == null) {

			resourceSet.getResourceFactoryRegistry().getContentTypeToFactoryMap()
					.put("org.eclipse.emf.ecore:contentType", new XMLContentHandlerImpl());

			Registry registry= resourceSet.getResourceFactoryRegistry();

			registry.getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl());
			registry.getExtensionToFactoryMap().put("xml", new XMLResourceFactoryImpl());
			registry.getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl());

		}
	}


}
