package edu.fichte.pbi.ide.commands;

import java.util.LinkedList;
import java.util.Scanner;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandler2;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;

import edu.fichte.pbi.ide.editors.PBIEditor;
import edu.fichte.pbi.ide.views.ConsoleView;

public class ExportCommandHandler implements IHandler, IHandler2 {

	java.util.List<Integer> deprecated = new LinkedList<Integer>();

	@Override
	public void setEnabled(Object evaluationContext) {
	}

	@Override
	public void addHandlerListener(IHandlerListener handlerListener) {
	}

	@Override
	public void dispose() {
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
		if (activeEditor instanceof PBIEditor) {
			PBIEditor pbi = (PBIEditor) activeEditor;
			Scanner scanner = new Scanner(pbi.text.getText());
			String result = "";
			int curLineNr = 1;
			while (scanner.hasNextLine()) {
				String curLine = scanner.nextLine();
				if (curLine.contains("EEPROM") && curLine.contains("DEBUG")
						|| curLine.contains("BREAKPOINT")
						|| curLine.contains("ASSERT")
						|| curLine.contains("ACTIVATEINFO")
						|| curLine.contains("DEACTIVATEINFO")) {
					curLine = "'" + curLine.trim();
				} else if (curLine.contains("NEW")
						|| curLine.contains("SYSCLOCK")) {
					deprecated.add(curLineNr);
				}
				result += curLine + "\n";
				curLineNr++;
			}
			scanner.close();
			pbi.text.setText(result);
			IWorkbenchWindow window = HandlerUtil
					.getActiveWorkbenchWindow(event);
			try {
				final ConsoleView console = (ConsoleView) window
						.getActivePage().showView(ConsoleView.ID);
				for (Integer lineNr : deprecated) {
					console.print("[Warn, line " + lineNr + "]You have to remove the referenced object and all it's assignments to export");
				}
			} catch (PartInitException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public boolean isEnabled() {
		return PlatformUI.getWorkbench().getActiveWorkbenchWindow()
				.getActivePage().getActiveEditor() instanceof PBIEditor;
	}

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

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {

	}

}
