package lc.esp.job;

import lc.mecha.http.server.HttpServer;
import lc.mecha.http.server.ListenerConfig;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import lc.mecha.security.CertificateKeyStore;

import java.util.Objects;

/**
 * @author Alex Leigh
 * @since mk20 (TOKYO PROTOCOL)
 */
public class ESPControlPlane {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ESPControlPlane.class);
    public static final String SSL_CERTIFICATE_ALIAS = HttpServer.SSL_CERTIFICATE_ALIAS;

    private final HttpServer ws;
    private int port = 52;
    private final CertificateKeyStore keyStore;

    public ESPControlPlane(CertificateKeyStore keyStore) {
        ws = new HttpServer();
        this.keyStore = keyStore;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        if (ws.isRunning()) {
            throw new IllegalStateException("setListenPort() called, but HTTP service already running.");
        }
        this.port = port;
    }

    public void start() {
        ws.addListener(new ListenerConfig(port, keyStore));
        ws.start();
        logger.info("ESP control plane started. [port: {}]", port);
    }

    @Override
    public String toString() {
        return "EspControlPlane{" +
                "ws=" + ws +
                ", port=" + port +
                ", keyStore=" + keyStore +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ESPControlPlane that = (ESPControlPlane) o;
        return port == that.port && Objects.equals(ws, that.ws) && Objects.equals(keyStore, that.keyStore);
    }

    @Override
    public int hashCode() {
        return Objects.hash(ws, port, keyStore);
    }
}