package org.etsi.mts.tdl.tools.to.docx.poi.ui.handlers;

import java.util.Arrays;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
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.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.xtext.ui.resource.IResourceSetProvider;
import org.etsi.mts.tdl.tools.to.docx.poi.Generator;

import com.google.inject.Inject;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class GenerationHandler extends AbstractHandler {
	 @Inject
	  IResourceSetProvider resourceSetProvider;

	 private IWorkbenchWindow window;

	/**
	 * The constructor.
	 */
	public GenerationHandler() {
	}
	
	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		IEditorInput input = HandlerUtil.getActiveEditorInput(event);
		IFile file = null;
		if (input != null && input instanceof FileEditorInput) {
			file = ((FileEditorInput) input).getFile();
		} else if (selection !=null && selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection) selection;
			Object firstElement = structuredSelection.getFirstElement();
			if (firstElement instanceof IFile) {
				file = (IFile) firstElement;
			}
		}
		
		if (file !=null) {
			URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
			ResourceSet rs = new ResourceSetImpl(); //TODO: use Xtext resource and resouce set?
			Resource r = rs.getResource(uri, true);
			EcoreUtil.resolveAll(r);
			
			ElementListSelectionDialog dialog = new ElementListSelectionDialog(Display.getDefault().getActiveShell(), new LabelProvider());
			dialog.setTitle("Generation Configuration");
			dialog.setMessage("Select template:");
			//TODO: get all templates from document
			dialog.setElements(new String[] { "TO_4_TABLE_TEMPLATE_EDITHELP", "TO_5_TABLE_TEMPLATE_ONEM2M", "TO_2_TABLE_TEMPLATE" });
			dialog.setInitialElementSelections(Arrays.asList(new String[] {Generator.selectedTemplate}));
			// user pressed cancel
			if (dialog.open() != Window.OK) {
				return false;
			} else {
				Object[] result = dialog.getResult();
				String selected = (String)result[0];
				Generator generator = new Generator();
				String target = file.getLocation().toOSString()+".docx";
				try {
					generator.generate(r, target, file.getName(), selected);
					MessageDialog.openInformation(
							Display.getDefault().getActiveShell(),
							"Generation Results",
							"Generated output in "+target);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					MessageDialog.openError(
							Display.getDefault().getActiveShell(),
							"Generation Results",
							"Generation failed! "+e.getMessage());
				}
				
				
			}
			
		}
		return null;
	}
	public void init(IWorkbenchWindow window) {
		this.window = window;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}
