package leigh.continuity.net;

import leigh.mecha.lang.DangerousRunnable;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.net.ServerSocket;
import java.net.Socket;

/**
 * This class implements a very basic TCP listener. Incoming connections are passed off to a
 * {@link SocketHandler}.
 *
 * @author Alex Leigh
 */
public class TcpListener implements DangerousRunnable {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(TcpListener.class);
    private final int port;
    private final SocketHandler socketHandler;

    public TcpListener(SocketHandler socketHandler, int port) {
        this.port = port;
        this.socketHandler = socketHandler;
    }

    @Override
    public void runDangerously() throws Exception {
        ServerSocket serverSocket = new ServerSocket(port);

        while (true) {
            Socket s = serverSocket.accept();
            logger.info("Connection rev'd. [socket: {}]", s);
            socketHandler.handle(s);
        }
    }

    @Override
    public void run() {
        try {
            runDangerously();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
