package org.gnunet.testing;

import org.gnunet.util.Client;
import org.gnunet.util.RelativeTime;
import org.gnunet.util.Server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ServerSocketChannel;

/**
 * Server with an ephemeral port.
 * Can spawn clients connected to the server for testing.
 *
 * @author Florian Dold
 */
public class TestingServer {
    public final Server server;
    private final ServerSocketChannel srvChan;

    public TestingServer() {
        this(RelativeTime.FOREVER, true);
    }

    public TestingServer(RelativeTime idleTimeout, boolean requireFound) {
        try {
            srvChan = ServerSocketChannel.open();
            srvChan.configureBlocking(false);

            // bind to ephemeral port
            srvChan.socket().bind(null);
        } catch (IOException e) {
            throw new RuntimeException("TestingServer creation failed");
        }

        server = new Server(idleTimeout, requireFound);
        server.addAcceptSocket(srvChan);

    }

    /**
     * Create a client connected to this server.
     *
     * @return a client connected to this server
     */
    public Client createClient() {
        SocketAddress socketAddress = srvChan.socket().getLocalSocketAddress();

        if (!(socketAddress instanceof InetSocketAddress)) {
            throw new RuntimeException("unknown type of socket address");
        }
        InetSocketAddress saddr = (InetSocketAddress) socketAddress;

        String hostname = saddr.getHostName();

        if (hostname == null) {
            throw new RuntimeException("localhost SocketAddress has no hostname");
        }

        return new Client(hostname, srvChan.socket().getLocalPort());
    }

}
