package vs;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketTimeoutException;
import java.util.Random;

/**
 * Server for var.sockets.udp.game.ReactionGameServer service. Waits a random time less than
 * MAX_WAITING_TIME_MS ms, then opens Gate for GATE_OPEN_DURATION_MS ms on port PORT, waiting for a
 * UDP packet to receive.
 *
 * @author Sandro Leuchter
 *
 */
public class ReactionGameServer {
  /**
   * port on which service is running on host
   */
  private static final int PORT = 4714;
  private static final int GATE_OPEN_DURATION_MS = 2000;
  private static final int MAX_WAITING_TIME_MS = 4000;
  private static final Random random = new Random(System.currentTimeMillis());
  /**
   * maximum size of payload in datagram
   */
  private static final int BUFSIZE = 512;

  /**
   * main method: entrypoint to run
   *
   * @param args
   *          ignored
   * @throws InterruptedException
   *           if interrupt during random sleeping period
   */
  public static void main(final String[] args) throws InterruptedException {
    try (DatagramSocket socket = new DatagramSocket(PORT)) {
      socket.setSoTimeout(GATE_OPEN_DURATION_MS);
      DatagramPacket packetIn = new DatagramPacket(new byte[BUFSIZE], BUFSIZE);

      System.out.println("Server gestartet ...");

      Thread.sleep(random.nextInt(MAX_WAITING_TIME_MS));
      boolean timeout = false;
      System.out.println("offen für Empfang");
      try {
        socket.receive(packetIn);
      } catch (SocketTimeoutException e) {
        timeout = true;
      }
      System.out.println("Empfang geschlossen");
      if (timeout) {
        System.out.println("nicht schnell genug!");
      } else {
        System.out.println("Paket hat es geschafft");
      }
    } catch (IOException e) {
      System.err.println(e);
    }
  }
}
