package tasks.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

public class Exec {

	public static boolean exec(final String commandLine, final boolean printOutput, final boolean printError,
			final long timeout, final File dir) throws TimeoutException {
		Process process = null;
		Worker worker = null;
		try {
			process = Runtime.getRuntime().exec(commandLine, null, dir);
			worker = new Worker(process);
			worker.start();

			worker.join(timeout);
			if (worker.exit != null)
				if (worker.exit == 0)
					return true;
				else
					return false;
			else
				throw new TimeoutException();
		} catch (InterruptedException | IOException ex) {
			worker.interrupt();
			Thread.currentThread().interrupt();
			return false;
		} finally {
			process.destroy();
		}
	}

	public static List<String> exec(String command, File dir) {
		System.out.println("Running command " + command);
		try {
			List<String> sb = new ArrayList<String>();
			String line;
			Runtime runtime = Runtime.getRuntime();
			Process p = runtime.exec("cmd /c " + command, null, dir);
			BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
			while ((line = input.readLine()) != null) {
				System.out.println(line);
				sb.add(line);
			}
			input.close();
			BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
			while ((line = error.readLine()) != null) {
				System.out.println(line);
			}
			error.close();
			p.waitFor();
			if (p.exitValue() == 0)
				return sb;

		} catch (IOException | InterruptedException e) {
			System.out.println("Error executing command: " + command);
			e.printStackTrace();
		}
		return null;
	}

}
