package edu.fichte.pbi.ide.commands;

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.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;

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

public class IntentCommandHandler implements IHandler, IHandler2 {

	@Override
	public void setEnabled(Object evaluationContext) {
		// TODO Auto-generated method stub

	}

	@Override
	public void addHandlerListener(IHandlerListener handlerListener) {
		// TODO Auto-generated method stub

	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
		if (activeEditor instanceof PBIEditor) {
			PBIEditor pbi = (PBIEditor) activeEditor;
			String intent = autoIntent(pbi.text.getText()); // TODO Zugriff
															// sch�ner machen
			pbi.text.setText(intent);

		}
		return null;
	}

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

	@Override
	public boolean isHandled() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {
		// TODO Auto-generated method stub

	}

	private static String autoIntent(String text) {
		String retVal = "";
		Scanner scanner = new Scanner(text);
		int intent = 0;
		while (scanner.hasNextLine()) {
			String line = scanner.nextLine().trim();
			String space = "";
			if (!line.startsWith("'")) {
				intentation: {
					int endLineComment = line.lastIndexOf("'");
					if (line.substring(
							0,
							endLineComment == -1 ? line.length()
									: endLineComment).trim().endsWith(":"))
						break intentation;
					for (int i = 0; i < intent; i++)
						space += " ";
					if (line.startsWith("FOR"))
						intent += 2;
					else if (line.startsWith("NEXT"))
						intent -= 2;
					if (intent < 0)
						intent = 0;
				}
			}
			retVal += space + line + "\n";
		}
		scanner.close();
		return retVal;
	}

}
