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

import java.io.IOException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.logging.Logger;

public class ServerSlice {
    private static final Logger logger = Logger.getLogger(ServerSlice.class.getName());
    private final DatagramChannel datagramChannel;
    private final Selector selector;
    private final int port;

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

    public void serve() throws IOException {
        // TODO bind and register the datagramChannels to the selector
        logger.info("ServerSlice started on port " + port);
        while (!Thread.interrupted()) {
            selector.select(this::treatKey);
        }
    }

    private void treatKey(SelectionKey key) {
        try {
            if (key.isValid() && key.isWritable()) {
                doWrite(key);
            }
            if (key.isValid() && key.isReadable()) {
                doRead(key);
            }
        } catch (IOException e) {
            // TODO
        }

    }

    private void doRead(SelectionKey key) throws IOException {
        // TODO
    }

    private void doWrite(SelectionKey key) throws IOException {
        // TODO
    }

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

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            usage();
            return;
        }
        new ServerSlice(Integer.parseInt(args[0])).serve();
    }
}
