import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * A single server thread.
 *
 * @author Matt Boutell, from Sun's Java Tutorial.
 *         Created Oct 15, 2006.
 */
public class KnockKnockServerThread extends Thread {

	private PrintWriter toClient;

	private Scanner fromClient;

	private KnockKnockProtocol kkp;

	/**
	 * Creates a new server thread.
	 *
	 * @param clientSocket
	 * @throws IOException
	 */
	public KnockKnockServerThread(Socket clientSocket) throws IOException {
		super();

		// We write to the client using its output stream. The second argument
		// means that output is flushed, rather than buffered.
		this.toClient = new PrintWriter(clientSocket.getOutputStream(), true);

		// We read input from the client using its input stream.
		this.fromClient = new Scanner(clientSocket.getInputStream());

		// The protocol handles the order of statements in knock-knock jokes.
		this.kkp = new KnockKnockProtocol();
	}

	@Override
	public void run() {
		String fromClientLine, toClientLine;

		// Asks "knock, knock" 
		toClientLine = this.kkp.processInput(null);
		this.toClient.println(toClientLine);

		// waits for input from the client.
		while (this.fromClient.hasNext()) {
			fromClientLine = this.fromClient.nextLine();
			System.out.println("Client said: " + fromClientLine);

			// checks to see if they follow knock-knock protocol
			toClientLine = this.kkp.processInput(fromClientLine);
			System.out.println("Server responds:" + toClientLine);

			this.toClient.println(toClientLine);

			// Occurs when the client says they don't want another joke.
			if (toClientLine.equals("Bye."))
				break;
		}
		// Close the streams.
		this.toClient.close();
		this.fromClient.close();
	}
}