package lc.esp.engine;

import lc.mecha.fabric.LiteralMessageSubscription;
import lc.mecha.http.client.HttpUtil;
import lc.mecha.http.server.HttpPipeline;
import lc.mecha.http.server.HttpServer;
import lc.mecha.http.server.ListenerConfig;
import lc.mecha.http.server.PrefixedHandler;
import lc.mecha.json.JSONObject;
import lc.mecha.lang.DangerousRunnable;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import lc.mecha.util.UniversalJob;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

/**
 * Enhanced Services Platform/ENGINE mk19
 * <p>
 * This is the core Engine class for the ESP service. Unlike previous versions of ESP, this implementation does
 * not harbor a <code>main()</code> class or offer a module system and is intended to be called from another
 * main service class.
 * <p>
 * ESP/Engine expects the <code>LC_ESP_ENGINE_CFG</code> environment variable to be set whose contents is a
 * URL to a JSON-format configuration file. The configuration file is expected to contain a JSON object with
 * the following parameters:
 * <p>
 * dir_host: The LDAP host to perform basic authentication against.
 * dir_username: The LDAP service account username.
 * dir_password: The LDAP service account password.
 * dir_search_base: The DN for the search-base to use when searching for LDAP users.
 * dir_domain: The domain-name in DNS format (e.g. gdn.leigh-co.com), used for assembling UPNs.
 *
 * @author Alex Leigh
 * @since mk20 (TOKYO PROTOCOL)
 */
public class ESPEngine implements DangerousRunnable {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ESPEngine.class);
    private final HttpServer ws;
    private final static String ENV_CFG = "LC_ESP_ENGINE_CFG";
    private final static String CFG_DIR_HOST = "dir_host";
    private final static String CFG_DIR_USER = "dir_username";
    private final static String CFG_DIR_PW = "dir_password";
    private final static String CFG_DIR_BASE = "dir_search_base";
    private final static String CFG_DIR_DOMAIN = "dir_domain";

    public ESPEngine() throws Exception {
        ws = new HttpServer(32);
        ws.addListener(new ListenerConfig(5252));

        String cfgUrl = System.getenv(ENV_CFG);
        if (cfgUrl == null) {
            logger.warn("LC_CFG_URL unset. Using default configuration.");
        } else {
            HttpClient httpClient = HttpUtil.makeOverlyTrustingClient(null);
            HttpResponse response = httpClient.execute(new HttpGet(cfgUrl));
            HttpEntity entity = response.getEntity();
            JSONObject cfg = new JSONObject(entity.getContent());

            // Intentionally unused
        }
    }

    public void register(PrefixedHandler handler) {
        ws.getWebPipeline().getServicePipeline().getSubscriptionBase().subscribe(
                new LiteralMessageSubscription<>(handler, HttpPipeline.KEY_SERVICE));
    }

    @Override
    public void runDangerously() {
        UniversalJob.banner(logger, "ESP/Engine mk20 (TOKYO PROTOCOL)", "Alex Leigh");
        ws.start();
    }

    @Override
    public void run() {
        runDangerously();
    }
}
