package jutil;

import java.util.*;
import java.io.*;
import java.net.*;
import jutil.*;

/**
 * A command line interface to a remote server.
 */
public class SimpleClient extends Correspondent {

	/**
	 * Standard input (the keyboard)
	 */
	protected BufferedReader stdin;
	/**
	 * Standard output (the console window)
	 */
	protected PrintWriter stdout;
	/**
	 * Standard error output (the console window)
	 */
	protected PrintWriter stderr;
	/**
	 * Connects client to some server, initializes standard I/O streams.
	 * @param host  Internet address of server's host.
	 * @param port  Server's port number.
	 */
	public SimpleClient(String host, int port) {
		requestConnection(host, port);
		stdout = new PrintWriter(
			new BufferedWriter(
					new OutputStreamWriter(System.out)), true);
		stderr = new PrintWriter(
			new BufferedWriter(
				new OutputStreamWriter(System.out)), true);
		stdin = new BufferedReader(
			new InputStreamReader(System.in));
	}
	/**
	 * Connects client to server running on local host.
	 * @param port  Server's port number.
	 */
	public SimpleClient(int port) { this("localhost", port); }

	/**
	 * Driver for console user interface. This method perpetually:
	 *   <ol>
	 *   <li> Reads user's command </li>
	 *   <li> Sends command to the server </li>
	 *   <li> Receives server's response </li>
	 *   <li> Displays server's response </li>
	 *   </ol>
	 */
	public void controlLoop() {
		while(true) {
			try {
				stdout.print("-> ");
				stdout.flush();
				String msg = stdin.readLine();
				if (msg == null) continue;
				if (msg.equals("quit")) break;
				stdout.println("sending: " + msg);
				send(msg);
				msg = receive();
				stdout.println("received: " + msg);
			} catch(IOException e) {
				stderr.println(e.getMessage());
				break;
			}
		}
		send("quit");
		stdout.println("bye");
	}
	/**
	 * Allows user to specify the server at the command line.
	 * The default host is localhost. The default port is 5555.
	 */
	public static void main(String[] args) {
		int port = 5555;
		String host = "localhost";
		if (1 <= args.length) {
			port = Integer.parseInt(args[0]);
		}
		if (2 <= args.length) {
			host = args[1];
		}
		SimpleClient client = new SimpleClient(host, port);
		client.controlLoop();
	}
}