package org.etsi.mts.tdl.ttcn3;

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.models.IModel;
import org.eclipse.epsilon.etl.EtlModule;
import org.etsi.mts.tdl.tdlPackage;
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/ttcn3mapping.etl";
			
			Bundle bundle = Platform.getBundle("org.etsi.mts.tdl.ttcn3");
			URL url = bundle.getEntry(source);

			EtlModule module = new EtlModule();
			module.parse(url.toURI());

			//TODO: integrate error reporting
			if (module.getParseProblems().size() > 0) {
				System.err.println("Parse errors occured...");
				for (ParseProblem problem : module.getParseProblems()) {
					System.err.println(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.dispose();
			//TODO: check if still necessary
			//module.reset();

		} catch (Exception e) {
			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;
	}

	
}
