package externalExecutor;

import java.io.*;

public class ThreadedStreamHandler extends Thread
{
	
  private String adminPassword;
  private InputStream inputStream;
  private PrintWriter printWriter;
  private StringBuilder outputBuffer = new StringBuilder();
  private boolean sudoIsRequested = false;
  
  public ThreadedStreamHandler(InputStream inputStream)
  {
    this.inputStream = inputStream;
  }
  
  /**
   * Use this constructor when you want to invoke the 'sudo' command.
   * The outputStream must not be null. If it is, you'll regret it. :)
   * 
   * TODO this currently hangs if the admin password given for the sudo command is wrong.
   * 
   * @param inputStream
   * @param streamType
   * @param outputStream
   * @param adminPassword
   */
  public ThreadedStreamHandler(InputStream inputStream, OutputStream outputStream, String adminPassword)
  {
    this.inputStream = inputStream;
    this.printWriter = new PrintWriter(outputStream);
    this.adminPassword = adminPassword;
    this.sudoIsRequested = true;
  }

    @Override
  public void run()
  {
    	
    if (sudoIsRequested)
    {
      //doSleep(500);
      printWriter.println(adminPassword);
      printWriter.flush();
    }
	BufferedReader bufferedReader = null;
	try
	{
	  bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
	  String line = null;
	  while ((line = bufferedReader.readLine()) != null)
	  {
	    outputBuffer.append(line + "\n");
	  }
	}
	catch (IOException e)
	{
	  e.printStackTrace();
	}
	catch (Throwable t)
	{
	  t.printStackTrace();
	}
	finally
	{
	  try
	  {
	    bufferedReader.close();
	  }
	  catch (IOException e)
	  {
	    e.printStackTrace();
	  }
	}
  }
  
  @SuppressWarnings("unused")
private void doSleep(long millis)
  {
    try
    {
      Thread.sleep(millis);
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }
  }
  
  public StringBuilder getOutputBuffer()
  {
    return outputBuffer;
  }

}




