// Author: Todd W. Neller

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class AmazonsServer {
	public static void main(String[] args) throws IOException {
		int port = 0;
		int i = 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 AmazonsServer ( ? | help | p[ort] <int> )*");
			else if (option.charAt(0) == 'p')
				port = Integer.parseInt(args[i++]);
			else {
				System.out.println("Unknown option: " + option);
				System.out.println("USAGE: java AmazonsServer ( ? | help | p[ort] <int> )*");
			}
		}
		Scanner scanner = new Scanner(System.in);
		if (port == 0) {
			System.out.print("Port? ");
			port = scanner.nextInt();
		}

		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			System.err.printf("Could not listen on port: %d.\n", port);
			System.exit(1);
		}

		Socket clientSocket = null;
		try {
			clientSocket = serverSocket.accept();
		} catch (IOException e) {
			System.err.println("Accept failed.");
			System.exit(1);
		}

		PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
		BufferedReader in = new BufferedReader(
				new InputStreamReader(
						clientSocket.getInputStream()));
		String inputLine;
		System.out.println("Connection accepted.");

		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.
		String response = "";
		int[] play = new int[3];
		while ((inputLine = in.readLine()) != null) {
			System.out.printf("Client said: %s\n", inputLine);
			Scanner lineIn = new Scanner(inputLine);
			String command = lineIn.next().trim();
			if (command.equalsIgnoreCase("init_game")) {
				player.init();
				response = player.getName();
			}
			else if (command.equalsIgnoreCase("get_play")) {
				long millisRemaining = lineIn.nextLong();
				play = player.getPlay(millisRemaining);
				response = String.format("%d %d %d", play[0], play[1], play[2]);
			}
			else if (command.equalsIgnoreCase("take_turn")) {
				play = new int[3];
				play[0] = lineIn.nextInt();
				play[1] = lineIn.nextInt();
				play[2] = lineIn.nextInt();
				player.takeTurn(play[0], play[1], play[2]);
				response = "OK";
			}
			out.println(response);
			System.out.printf("Server response: %s\n", response);
		}
		out.close();
		in.close();
		clientSocket.close();
		serverSocket.close();

	}
}
