import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;

/**
 * A simple interactive tester for character sequences.  You
 * pass a character sequence to this class and it gives you a
 * simple textual interface.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of Octboer 2002
 */
public class CharStreamTester {
  // +--------+-------------------------------------------------------------
  // | Fields |
  // +--------+

  /**
   * The object used to read input (presumably from the keyboard.
   */
  protected SimpleInput in;

  /**
   * The object used to write output (presumably to the screen).
   */
  protected SimpleOutput out;

  /**
   * The character sequence we're testing.
   */
  protected AdvCharStream cs;

  // +--------------+-------------------------------------------------------
  // | Constructors |
  // +--------------+

  /**
   * Build a new tester to test the specified character stream.
   */
  public CharStreamTester(AdvCharStream cs) {
    this.cs = cs;
    this.in = new SimpleInput();
    this.out = new SimpleOutput();
  } // CharStreamTester(AdvCharStream)


  // +---------+------------------------------------------------------------
  // | Methods |
  // +---------+

  /**
   * Run the tester.
   */
  public void interact() {
    boolean done = false;	// Are we done getting input?
    String response;		// A response typed by the user
    char resp;			// The first character of that response

    // Keep going until the user indicates we're done
    while (!done) {
      // Print a prompt
      out.print("[line: " + cs.line() + ", pos: " + cs.pos() + "]> ");
      // Get the response
      response = in.readLine();
      if (response.length() != 0) {
        // Decide what to do based on that response
        switch (response.charAt(0)) {
          case 'h':				// Help
          case '?':
            out.println("h: print this help message");
            out.println("p: peek at the next character");
            out.println("n: read the next character");
            out.println("c: check for end of input");
            break;
          case 'p':
            try {
              char ch = cs.peek();
              out.println("Next character '" + ch + "'");
            }
            catch (Exception e) {
              out.println("Sorry, no characters remain.");
            } // catch
            break;
          case 'n':
            try {
              char ch = cs.next();
              out.println("Next character '" + ch + "'");
            }
            catch (Exception e) {
              out.println("Sorry, no characters remain.");
            } // catch
            break;
          case 'q':
            done = true;
            break;
        } // switch (response.charAt(0))
      } // if (response.length() != 0)
    } // while
  } // interact()
} // class CharStreamTester

