/* **********************************
 *   StreamWatcher.java
 *     StreamWatcher
 * **********************************/
package admin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/** Monitors the given InputStream, printing it to System.out.
 *    Runs until done() is called.
 *  @author Alex Dubreuil
 */
public class StreamWatcher extends Thread{
    private BufferedReader reader;
    
    /** Note: done is changed only through the done() method
     *    Which should only be called by the parent Thread of this. */
    private Boolean done = false;
    private Output out;
    
    /** Constructor */
    public StreamWatcher(InputStream s, Output o){
        reader = new BufferedReader(new InputStreamReader(s));
        out = o;
        start();
    }
    
    /** Called by parent Thread to wait for completion. */
    public synchronized boolean isDone(){ return done; }
    
    /** Called by parent Thread to terminate this thread. */
    public synchronized void kill(){ this.done = true; }
    
    /** Required by Runnable interface.
     *  Begins monitoring the given InputStream. */
    public void run(){
        while(!isDone()){
            try{
                // Wait until there's something to read.

                // As long as done() hasn't be called.
                while(!reader.ready() && !isDone()){ Thread.yield(); }    
                while(reader.ready() && !isDone()){
                    // Read/Write it.
                    String s = reader.readLine();
                    if(s == null){
                        done = true;
                        break;
                    }
                    out.println("      "+s);
                }
            }catch(IOException e1){ e1.printStackTrace(); }
        }
    }
}