package org.etsi.mts.tdl.execution.java.eclipse.commands;

import java.io.IOException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;
import org.etsi.mts.tdl.Package;
import org.etsi.mts.tdl.execution.java.codegen.JUnitTestGenerator;
import org.etsi.mts.tdl.execution.java.codegen.Settings;
import org.etsi.mts.tdl.execution.java.eclipse.ui.PropertyPage;
import org.osgi.service.prefs.Preferences;

public class RenderHandler extends AbstractHandler implements IHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IFile tdl = null;
		
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
			Object element = ((IStructuredSelection) selection).getFirstElement();
			if (element instanceof IFile) {
				String ext = ((IFile) element).getFileExtension();
				if (ext.toLowerCase().contains("tdl")) {
					tdl = (IFile) element;
				}
			}
		}
		if (tdl == null)
			return null;

		ResourceSet rs = new ResourceSetImpl();
		URI uri = URI.createPlatformResourceURI(tdl.getFullPath().toString(), true);
		Resource resource = rs.getResource(uri, true);
//		((org.eclipse.xtext.linking.lazy.LazyLinkingResource)resource).
		EcoreUtil.resolveAll(resource);
		Package model = (Package) resource.getContents().get(0);

		ProjectScope ps = new ProjectScope(tdl.getProject());
		Preferences preferences = ps.getNode(PropertyPage.PREFERENCE_SCOPE);

		IContainer root = ResourcesPlugin.getWorkspace().getRoot();
		final IFolder generationDir = root.getFolder(new Path(preferences.get(Settings.OUTPUT_DIR, "")));
		Settings settings = new Settings(preferences.get(Settings.OUTPUT_DIR, ""),
				generationDir.getLocation().toFile(),
				preferences.get(Settings.PACKAGE, ""),
				preferences.get(Settings.INJECTOR, ""),
				preferences.get(Settings.DATE_FORMAT, ""),
				preferences.get(Settings.USE_MAPPING, ""),
				preferences.getBoolean(Settings.UNMAPPED_DATA, false));
		
		JUnitTestGenerator generator = new JUnitTestGenerator(model, settings);

		final String taskName = "Render JUnit";
		final Job j = new Job(taskName) {
			@Override
			public IStatus run(final IProgressMonitor monitor) {
				try {
					generator.generate();
				} catch (IOException e) {
					return new Status(IStatus.ERROR, getClass(), taskName +  " failed", e);
				}
				
				try {
					generationDir.refreshLocal(IResource.DEPTH_INFINITE, monitor);
				} catch (CoreException e) {
					return e.getStatus();
				}
				
				return Status.OK_STATUS;
			}
		};

		j.setUser(true);
		j.setPriority(Job.INTERACTIVE);

		j.schedule();
		
		return null;
	}

}
