package fr.uge.net.udp.exam2223.ex2;


import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.nio.channels.DatagramChannel;
import java.util.logging.Logger;

public class ServerChat {

    private static final Logger logger = Logger.getLogger(ServerChat.class.getName());
    private final DatagramChannel datagramChannel;
    private final int port;

    public ServerChat(int port) throws IOException {
        this.datagramChannel = DatagramChannel.open();
        this.port = port;
    }

    public void serve() throws IOException {
        datagramChannel.bind(new InetSocketAddress(port));
        System.out.println("ServerChat started on port " + port);
        // TODO
    }

    public static void usage() {
        System.out.println("Usage : ServerChat port");
    }

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            usage();
            return;
        }
        int port = Integer.valueOf(args[0]);
        if (!(port >= 1024) & port <= 65535) {
            System.out.println("The port number must be between 1024 and 65535");
            return;
        }

        var server=new ServerChat(port);
        try {
            server.serve();
        } catch (BindException e) {
            System.err.println("Server could not bind on " + port + "\nAnother server is probably running on this port.");
            return;
        }
    }
}
