package com.roguewave.jchat;
import java.io.*;

/**
 * The Reader class.
 * <P>
 * The Reader class is implemented as a specialized Thread with the sole
 * responsibility of monitoring incoming data on an instance of a DataInputStream.
 * The Reader reads in lines (terminated with '\n') as separate commands that make
 * up a command set.  The Dispatcher is notified once a complete command set is
 * received from the DataInputStream.
 * </P>
 *
 * @see          java.io.DataInputStream
 * @see          com.roguewave.jchat.Dispatcher
 *
 * @version      1.0  96 April 4
 * @author       Eldon J. Metz
 */
public class Reader extends Thread {
  private Dispatcher        dispatcher_;
  private DataInputStream   inputStream_;
  private int               numCommands_;				

  /**
   * Creates a Reader.  The Reader monitors the specified DataInputStream until the
   * specified number of commands are received.  The specified Dispatcher is then
   * asked to process the command.
   */
  public Reader(DataInputStream aInputStream, int aInt, Dispatcher aDispatcher) {
    inputStream_ = aInputStream;
	numCommands_ = aInt;
	dispatcher_ = aDispatcher;
  }

  /**
   * The body of the Reader.  Continuously monitors a non-null input stream,
   * alerting a Dispatcher when a complete command set is received.
   */
  public void run() {
    while (inputStream_ != null) {
	  String[] command = new String[numCommands_];
	  for (int i = 0; i < numCommands_; i++) {
	    command[i] = readData();
	  }
	  dispatcher_.processCommand(command);
	}
  }

  /**
   * Helper method for reading data from the input stream. This method should not be used
   * by any method other than this.run() after the thread for an instance of a Reader is
   * started.
   */
  public String readData() {
    String buffer = "";

    try {
	  buffer = inputStream_.readLine();
	} catch (IOException ioe) {
      System.out.println("Reader: " + ioe);
	}
	return buffer;
  }
}
