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.swt.custom.StyledText;
import org.eclipse.swt.graphics.Point;
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 CommentCommandHandler implements IHandler, IHandler2 {

	@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;
			StyledText text = pbi.getText();
			Point selectionRange = text.getSelection();
			int from = selectionRange.x;
			int to = selectionRange.y;
			String selection = text.getText().substring(from, to);
			Scanner scanner = new Scanner(selection);
			// List<String> lines = new LinkedList<>();
			// boolean uncomment = true;
			String replacement = "";

			while (scanner.hasNextLine()) {
				String actual = scanner.nextLine();
				replacement += (actual.startsWith("'") ? "" : "'") + actual
						+ (scanner.hasNextLine() ? "\n" : "");
				// uncomment &= s.startsWith("'");
				// lines.add(s);
			}
			// for (String actual : lines) {
			// replacement += (uncomment ? actual.substring(1) : "'" + actual)
			// + "\n";
			// }
			text.setText(text.getText().replaceAll(selection, replacement));
			scanner.close();
		}
		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) {
		// TODO Auto-generated method stub

	}

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

	}

}
