import java.io.*;
import javax.swing.*;

final class a3test {

  private static void sleeper(long time) {
    try {Thread.currentThread().sleep(time);}
    catch(Exception e) {}
  }

  private static void startServer() {
    new Thread(new Runnable() {
        public void run() {
          a3testServer.start(JavlleServer.DEFAULT_PORT);
        }
      }).start();
  }

  private static void startClient() {
    new Thread(new Runnable() {
        public void run() {
          a3testClient.start("localhost", JavlleServer.DEFAULT_PORT);
        }
      }).start();
  }

  public static void main(String args[]) {
    startServer();
    sleeper(500);
    startClient();
    sleeper(500);
    startClient();
  }
}



final class a3testServer {

  public static void main(String args[]) {
    // extract port parameter
    int port=JavlleServer.DEFAULT_PORT;
    try {
      port=Integer.parseInt(args[0]);
    }
    catch (ArrayIndexOutOfBoundsException e) {}
    catch (NumberFormatException e) {
      System.err.println("Invalid port number");
    }
    start(port);
    System.exit(0);
  }

  public static void start(int port) {
    try {
      JavlleServer js=new JavlleServer(port);
      js.listen();
    }
    catch (IOException e) {
      System.err.println("Error starting server");
    }
  }
}



final class a3testClient {

  public static void main(String args[]) {
    String host="localhost";
    int port=JavlleServer.DEFAULT_PORT;
    try {
      host=args[0];
      port=Integer.parseInt(args[1]);
    }
    catch (ArrayIndexOutOfBoundsException e) {}
    catch (NumberFormatException e) {
      System.err.println("Invalid port number");
    }
    start(host, port);
    System.exit(0);
  }

  public static void start(String host, int port) {
    JFrame frame=null;
    try {
      Board board=new Board();
      JavlleClient jc=new JavlleClient(host, port);
      frame=BoardView.createPlayerWindow(board, jc);
      jc.boardListen(board);
    }
    catch (IOException e) {
      System.err.println("Error starting client");
    }
    if(frame!=null) {
      frame.dispose();
    }
    frame=null;
  }
}
