package ub.scp2.externalExecutor;

import java.io.*;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletContext;


public class ExternalExecutor {
	private List<String> command;
	private ThreadedStreamHandler inputStreamHandler;
	private ThreadedStreamHandler errorStreamHandler;
	private String run_path;
	  
    public ExternalExecutor(final List<String> commandInformation, String path){
    	if (commandInformation==null) throw new NullPointerException("Wrong command syntax.");
	    this.command = commandInformation;
	    this.run_path = path;
	}

	public int executeCommand() {
		
		int exitValue = -99;

	    try
	    {
	      ProcessBuilder pb = new ProcessBuilder(command);
	      pb.directory(new File(run_path));
	      Process process = pb.start();

	      //Get stdin, stdout and stderr
	      OutputStream stdOutput = process.getOutputStream();
	      InputStream inputStream = process.getInputStream();
	      InputStream errorStream = process.getErrorStream();

	      //Create handlers
	      inputStreamHandler = new ThreadedStreamHandler(inputStream);
	      errorStreamHandler = new ThreadedStreamHandler(errorStream);

	      inputStreamHandler.start();
	      errorStreamHandler.start();

	      //Wait for the process to give a return vaule
	      exitValue = process.waitFor();
	 
	      //Stop and join the threads
	      inputStreamHandler.interrupt();
	      errorStreamHandler.interrupt();
	      inputStreamHandler.join();
	      errorStreamHandler.join();
	    }
	    catch (IOException e)
	    {
	    	e.printStackTrace();
	    }
	    catch (InterruptedException e)
	    {
	    	e.printStackTrace();
	    }
	    finally
	    {
	      return exitValue;
	    }
	  }

    //Return standard output
	public StringBuilder getStandardOutputFromCommand(){
	    return inputStreamHandler.getOutputBuffer();
	}

	//return standard error
    public StringBuilder getStandardErrorFromCommand(){
    	return errorStreamHandler.getOutputBuffer();
	  }
}
