// Author: Todd W. Neller

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class AmazonsClient {
	public static void main(String[] args) throws IOException {
		String host = "";
		int port = 0;
		int i = 0;
		int seconds = 0;
		while (i < args.length) {
			String option = args[i++].toLowerCase();
			if (option.equalsIgnoreCase("?") || option.equalsIgnoreCase("-?") || option.equalsIgnoreCase("help") || option.equalsIgnoreCase("-help"))
				System.out.println("USAGE: java AmazonsClient ( ? | help | h[ost] <string> | p[ort] <int> |  s[econds] <int> )*");
			else if (option.charAt(0) == 'h')
				host = args[i++];
			else if (option.charAt(0) == 'p')
				port = Integer.parseInt(args[i++]);
			else if (option.charAt(0) == 's')
				seconds = Integer.parseInt(args[i++]);
			else {
				System.out.println("Unknown option: " + option);
				System.out.println("USAGE: java AmazonsClient ( ? | help | h[ost] <string> | p[ort] <int> |  s[econds] <int> )*");
			}
		}
		Scanner scanner = new Scanner(System.in);
		if (host.equals("")) {
		System.out.print("Target host? ");
		host = scanner.nextLine().trim();
		}
		if (port == 0) {
		System.out.print("Port? ");
		port = scanner.nextInt();
		}
		Socket socket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			socket = new Socket(host, port);
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host: " + host + ".");
			System.exit(1);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for "
					+ "the connection to: " + host + ".");
			System.exit(1);
		}
		System.out.printf("Connected to %s on port %d.\n", host, port);
		
		// Initialize game and 1st player
		if (seconds == 0) {
			System.out.print("Game time (seconds)? ");
			seconds = scanner.nextInt();
		}
		long totalMillis = 1000 * seconds;
		long[] millisRemaining = {totalMillis / 2, totalMillis / 2};
		AmazonsState state = new AmazonsState(); // The state provides us the current state of play.
		AmazonsPlayer player = state; // The player acts on the state, but may be a separate entity.
		player.init();
		String[] playerNames = {player.getName(), ""};
		System.out.println("White: " + playerNames[0]);
		out.println("init_game " + playerNames[0]);
		playerNames[1] = in.readLine().trim();
		System.out.println("Black: " + playerNames[1]);
		System.out.println();
		int[] play;
		int moveCount = 1;
		while (state.hasLegalMove()) {
			System.out.println(state.boardToString());
			if (state.getPlayer() == AmazonsState.WHITE) { // Client plays White.
				long startTime = System.currentTimeMillis();
				play = player.getPlay(millisRemaining[0]);
				long turnTime = System.currentTimeMillis() - startTime;
				millisRemaining[0] -= turnTime;
				if (millisRemaining[0] < 0) {
					System.out.println("White has run out of time. Black wins.");
					System.exit(2);
				}
			}
			else {
				out.println("get_play " + millisRemaining[1]);
				long startTime = System.currentTimeMillis();
				String playString = in.readLine();
				long turnTime = System.currentTimeMillis() - startTime;
				millisRemaining[1] -= turnTime;
				if (millisRemaining[1] < 0) {
					System.out.println("Black has run out of time. White wins.");
					System.exit(1);
				}
				Scanner playScanner = new Scanner(playString);
				play = new int[3];
				play[0] = playScanner.nextInt();
				play[1] = playScanner.nextInt();
				play[2] = playScanner.nextInt();
			}
			System.out.println(moveCount++ + ". " + state.moveToString(play[0], play[1], play[2]) + "\n");
			out.println(String.format("take_turn %d %d %d", play[0], play[1], play[2]));
			String response = in.readLine();
			if (!response.trim().equalsIgnoreCase("ok")) {
				System.err.printf("Error: Client said \"%s\". Play not acknowledged. Terminating.", response);
				System.exit(3);
			}
			player.takeTurn(play[0], play[1], play[2]);
		}
		System.out.println(state.boardToString());
		System.out.printf("%s wins.\n", state.getWinner() == AmazonsState.WHITE ? "White" : "Black");
		out.close();
		in.close();
		socket.close();
	}
}
