package org.etsi.mts.tdl.ttcn3;

import java.net.URI;
import java.net.URL;

import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.epsilon.common.parse.problem.ParseProblem;
import org.eclipse.epsilon.emc.emf.EmfModel;
import org.eclipse.epsilon.emc.emf.InMemoryEmfModel;
import org.eclipse.epsilon.eol.exceptions.EolRuntimeException;
import org.eclipse.epsilon.eol.models.IModel;
import org.eclipse.epsilon.etl.EtlModule;
import org.etsi.mts.tdl.tdlPackage;
import org.etsi.mts.tdl.resources.ResourceHandler;
import org.osgi.framework.Bundle;

import de.ugoe.cs.swe.tTCN3.TTCN3Package;

public class Transform {
	public void transform(Resource r, Resource tr) {
		try {
			//load transformation scripts
			String source = "epsilon/ttcn3/ttcn3mapping.etl";
			URI uri = ResourceHandler.getSourceUri(this.getClass(), "org.etsi.mts.tdl.ttcn3", source);

			EtlModule module = new EtlModule();
			module.parse(uri);

			//TODO: integrate error reporting
			if (module.getParseProblems().size() > 0) {
				System.err.println("Parse errors occured...");
				for (ParseProblem problem : module.getParseProblems()) {
					System.err.println("  ETL: "+problem.toString());
				}
			}
			
			//load models
			IModel tdlModel = getTDLModel(r, true, false);
			IModel ttcnModel = getTTCNModel(tr, false, true);
			tdlModel.load();
			ttcnModel.load();
			module.getContext().getModelRepository().addModel(tdlModel);
			module.getContext().getModelRepository().addModel(ttcnModel);

			//execute
			module.execute();
			
			tdlModel.dispose();
//			ttcnModel.store();
			ttcnModel.dispose();
			//TODO: check if still necessary
			//module.reset();

		} catch (EolRuntimeException e) {
			System.err.println("  EOL: "+e.getAst().getModule().getSourceUri().getPath()+" : "+e.getLine() +" : "+e.getMessage()+"");
		} catch (Exception e) {
			System.err.println("  Transformation: "+e.getMessage());
			//e.printStackTrace();
		}
		
	}
	
	//TODO: extract to shared library
	public IModel getTDLModel(Resource resource, boolean read, boolean write) throws Exception {
		EmfModel model;
		model = new InMemoryEmfModel("TDL", resource, tdlPackage.eINSTANCE);
		model.setStoredOnDisposal(write);
		model.setReadOnLoad(read);
		model.setCachingEnabled(true);
		return model;
	}

	public IModel getTTCNModel(Resource resource, boolean read, boolean write) throws Exception {
		EmfModel model;
		model = new InMemoryEmfModel("TTCN", resource, TTCN3Package.eINSTANCE);
		model.setStoredOnDisposal(write);
		model.setReadOnLoad(read);
		model.setCachingEnabled(true);
		return model;
	}

	
}
