package net.hexid.hexbot.bot;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import net.hexid.Utils;

public abstract class BotProcess extends Thread {
	private Process process;
	private Scanner in;
	protected Bot bot;

	public BotProcess(Bot bot) throws IOException {
		super();
		this.bot = bot;
		this.process = startProcess();
		this.in = new Scanner(this.process.getInputStream());
	}

	protected abstract void processInput(final String in);

	protected Process startProcess() throws IOException {
		List<String> botExecuteData = bot.getBotExecuteData();
		botExecuteData.add(0, "casperjs"); // program (will be added to PATH)
		botExecuteData.add(1, Bots.getBotFile(bot));

		String processData = Utils.join(" ", botExecuteData);
		String pathName;
		if(File.pathSeparator.equals(";")) { // if windows
			pathName = "Path";
			botExecuteData = Arrays.asList(new String[]{"cmd.exe", "/C", processData});
		} else { // if unix-based
			pathName = "PATH";
			botExecuteData = Arrays.asList(new String[]{"/usr/bin/env","bash", "-c", processData});
		}

		// create a processbuilder with the bot's commands and combined input and error streams
		ProcessBuilder pb = new ProcessBuilder(botExecuteData).redirectErrorStream(true);

		// append phantomjs and casperjs to the path (runs local installs first)
		pb.environment().put(pathName, Bots.getBotEnvPath(pb.environment().get(pathName)));

		return pb.start(); // execute the process
	}

	@Override public void run() {
		while(in.hasNext())
			processInput(in.nextLine());

		in.close();

		try {
			process.waitFor();
			bot.processExitCode(process.exitValue());
		} catch(InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void killProcess() {
		process.destroy();
	}
}
@@ -592,193 +592,101 @@
 ng%3E 
-botExecuteData = bot.getBotExecuteData();%0A%09%09botExecuteData.add(0, %22casperjs%22); // program (will be added to PATH)%0A%09%09botExecuteData.add(1, Bots.getBotFile(bot));%0A%0A%09%09String processData = 
+processData;%0A%09%09String botExecuteData = Utils.join(%22 %22, %22casperjs%22, Bots.getBotFile(bot),%0A%09%09%09%09
 Util
@@ -696,24 +696,31 @@
 oin(%22 %22, bot
+.getBot
 ExecuteData)
@@ -718,16 +718,19 @@
 cuteData
+())
 );%0A%09%09Str
@@ -817,34 +817,31 @@
  %22Path%22;%0A%09%09%09
-botExecute
+process
 Data = Array
@@ -879,23 +879,26 @@
 , %22/C%22, 
-process
+botExecute
 Data%7D);%0A
@@ -950,26 +950,23 @@
 TH%22;%0A%09%09%09
-botExecute
+process
 Data = A
@@ -1020,23 +1020,26 @@
 , %22-c%22, 
-process
+botExecute
 Data%7D);%0A
@@ -1174,26 +1174,23 @@
 Builder(
-botExecute
+process
 Data).re

Allow for the use of bot.getBotExecuteData() returning String[] instead of ArrayList<String>