package leigh.esp.kabe.http;

import leigh.esp.kabe.KabeServer;
import leigh.esp.kabe.ServiceBus;
import leigh.esp.kensho.KenshoService;
import leigh.esp.tokei.TokeiService;
import leigh.mecha.fabric.LiteralMessageSubscription;
import leigh.mecha.http.server.WebPipeline;
import leigh.mecha.http.server.WebServer;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.util.HashSet;
import java.util.Properties;

/**
 * This HTTP bus contains services which are embedded with the Kabe server, but could be split off into seperate
 * servers at a later time. In this manner they are distinct than {@link leigh.esp.kabe.Service} objects.
 *
 * @author Alex Leigh
 */
public class PrivateHttpBus implements ServiceBus {
    private final static MechaLogger logger = MechaLoggerFactory.getLogger(PrivateHttpBus.class);
    private final WebServer webserver;

    public PrivateHttpBus(KabeServer kabe, int port) {
        webserver = new WebServer(port, 128);
        setupTokeiDoor(webserver);
        setupKenshoDoor(webserver, kabe.getProperties());
    }

    private void setupTokeiDoor(WebServer webserver) {
        HashSet<String> prefixes = new HashSet<>();
        prefixes.add("/tokei");
        TokeiService door = new TokeiService(prefixes);
        webserver.getWebPipeline().getServicePipeline().getSubscriptionBase().subscribe(
                new LiteralMessageSubscription<>(door, WebPipeline.KEY_SERVICE));
    }

    private void setupKenshoDoor(WebServer webserver, Properties properties) {
        HashSet<String> prefixes = new HashSet<>();
        prefixes.add("/kensho");
        KenshoService door = new KenshoService(prefixes, properties);
        webserver.getWebPipeline().getServicePipeline().getSubscriptionBase().subscribe(
                new LiteralMessageSubscription<>(door, WebPipeline.KEY_SERVICE));
    }

    @Override
    public void start() {
        webserver.start();
    }

}
