package org.etsi.mts.tdl.openapi.generator.ui.handlers;

import java.util.Arrays;
import java.util.LinkedHashMap;

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.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;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class GeneratorHandler extends AbstractHandler {

	LinkedHashMap<String, String> targetFormats = new LinkedHashMap<>();

	public static String translationTarget = "java";
	
	private IWorkbenchWindow window;

	/**
	 * The constructor.
	 */
	public GeneratorHandler() {
		init();
	}

	private void init() {
		//TODO: update rt.ui as well
		//TODO: do not reload after first init
		if (!targetFormats.isEmpty()) {
			return;
		}
		targetFormats.clear();
		
		for (String gen : OpenAPIGeneratorLauncher.listGenerators()) {
			targetFormats.put(gen, gen);
		}
	}

	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		init();
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		IEditorInput input = HandlerUtil.getActiveEditorInput(event);
		IFile file = null;
		if (input != null && input instanceof FileEditorInput && ((FileEditorInput) input).getFile().getName().endsWith("yaml")) {
			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 && file.getName().endsWith("yaml")) {
			
			String selectedTarget = null;
			
			IFile javaConfig = file.getProject().getFile("openapi-codegen-config-impl.json");
			if (javaConfig.exists()) {
				selectedTarget = "java";
			}
			
			if (selectedTarget == null) {
				ElementListSelectionDialog dialog = new ElementListSelectionDialog(Display.getDefault().getActiveShell(), new LabelProvider());
				dialog.setTitle("OpenAPI Generator Target Selection");
				dialog.setMessage("Generating assets from "+file.getName()
									+"\n\nSelect the target format");
				dialog.setElements(targetFormats.keySet().toArray());
				
				dialog.setInitialElementSelections(Arrays.asList(new String[] {GeneratorHandler.translationTarget}));
				
				// user pressed cancel
				if (dialog.open() != Window.OK) {
					return false;
				} else {
					//TODO: enable validation once it does not exit
//					OpenAPIGeneratorLauncher.validate(file.getLocation().toFile().getAbsolutePath());
//					OpenAPIGeneratorLauncher.parse(file.getLocation().toFile().getAbsolutePath());
					
					Object[] result = dialog.getResult();
					selectedTarget = (String)result[0];
				}
				
			}
			//TODO: add option to skip validation
			//TODO: add step to validate

			if (selectedTarget != null) {
				translationTarget = selectedTarget;
				if (javaConfig.exists())
					OpenAPIGeneratorLauncher.launch(file.getLocation().toFile(), javaConfig.getLocation().toFile(), selectedTarget);
				else
					OpenAPIGeneratorLauncher.launch(file.getLocation().toFile().getAbsolutePath(), selectedTarget);
			}
		}
		return null;
	}
	
	public void init(IWorkbenchWindow window) {
		this.window = window;
	}

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

}
