import java.io.*;
import java.net.*;

/** A command-line client for ChatServer. */
public class ChatClient {

  // TODO: Make this into a command-line parameter.
  public static final String HOST = "localhost";

  /** Program that acts as a listening or speaking client for ChatServer. */
  public static void main(String[] args) throws IOException {
    if (args.length != 1) {
      System.err.println("Usage: ChatClient listen|speak");
      System.exit(1);
    }

    if (args[0].equals("listen")) {
      listenForever();
    } else if (args[0].equals("speak")) {
      speak(readLine());
    } else {
      System.err.println("Unknown client type '" + args[0] + "'");
      System.err.println();
      System.err.println("Usage: ChatClient listen|speak");
      System.exit(1);
    }
  }

  /** Writes the given line to the chat room. */
  private static void speak(String line) throws IOException {
    Socket socket = new Socket(HOST, ChatServer.PORT);
    Writer writer = new OutputStreamWriter(socket.getOutputStream());
    writer.write("speak " + line + "\n");
    writer.flush();
    socket.close();
  }

  /**
   * Sets up a listening socket in the chat room and then prints out each line
   * that is said.
   */
  private static void listenForever() throws IOException {
    Socket socket = new Socket(HOST, ChatServer.PORT);

    Writer writer = new OutputStreamWriter(socket.getOutputStream());
    writer.write("listen\n");
    writer.flush();

    BufferedReader reader =
        new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null)
      System.out.println(line);
  }

  /** Reads one line of input from System.in and returns it. */
  private static String readLine() throws IOException {
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(System.in));
    return reader.readLine();
  }
}