package edu.fichte.pbi.ide.commands;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.osgi.framework.Bundle;

import edu.fichte.pbi.ide.Activator;
import edu.fichte.pbi.ide.views.ConsoleView;
import edu.fichte.pbi.ide.views.HelpView;

public class DebugSchemeCommandHandler implements IHandler, IHandler2 {

	@Override
	public void setEnabled(Object evaluationContext) {

	}

	@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 {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		try {
			final ConsoleView console = (ConsoleView) window.getActivePage()
					.showView(ConsoleView.ID);
			Bundle bundle = Activator.getDefault().getBundle();
			File targetRoot = bundle.getDataFile("");
			File file = new File(targetRoot, "config/color.cfg");
			if (!file.canRead()) {
				HelpView.copyPathFromBundleToFSRecursive(bundle, "config",
						targetRoot);
			}
			String s = "";
			Scanner scanner = new Scanner(file);
			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				if (line.startsWith("##") || line.isEmpty())
					continue;
				if (line.contains("console scheme")) {
					String[] split = line.split("=");
					if (split.length != 2) {
						scanner.close();
						throw new IllegalArgumentException();
					}
					split[1] = split[1].trim().equals("blue") ? " white"
							: split[1].trim().equals("white") ? " black"
									: split[1].trim().equals("black") ? "blue"
											: null;
					split[1] = split[1] == null ? "blue" : split[1];
					line = split[0] + "=" + split[1];
				}
				s += line + "\n";
			}
			scanner.close();
			try {
				FileOutputStream out = new FileOutputStream(file);
				out.write(s.getBytes());
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			console.setScheme();
		} catch (PartInitException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

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

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

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {

	}
}
