package leigh.esp.keikai.service;

import leigh.eo.EO;
import leigh.eo.json.JsonInput;
import leigh.esp.kabe.KabeServer;
import leigh.esp.kabe.Service;
import leigh.esp.kabe.http.ProxyService;
import leigh.esp.keikai.sdk.KeikaiClient;
import leigh.mecha.http.server.WebTransaction;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;

/**
 * Implementation of the Keikai discovery & health monitoring service.
 *
 * @author Alex Leigh
 */
public class KeikaiService implements Service {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(KeikaiService.class);
    private final KabeServer kabe;

    public KeikaiService(KabeServer kabe) {
        this.kabe = kabe;
    }

    @Override
    public void handleClientRequest(WebTransaction clientRequest) throws IOException {
        // We don't check the request, path, so we actually service anything that makes it here.
        try {
            JsonInput foi = new JsonInput(clientRequest.httpServletRequest.getInputStream());
            EO request = foi.readEo();
            // TODO: Verify request

            String dstUrl = request.getValueString(KeikaiClient.DST_URI);
            String srcUri = request.getValueString(KeikaiClient.SRC_URI);

            Service s = new ProxyService(kabe.getEgressClient(), dstUrl, srcUri);
            kabe.updateService(s);
        } catch (IOException | URISyntaxException e) {
            logger.warn("Malformed request: e", e);
            clientRequest.httpServletResponse.setStatus(400);
            clientRequest.httpServletResponse.getOutputStream().write("Invalid request.".getBytes(StandardCharsets.UTF_8));
        }
    }

    @Override
    public Instant lastKnownGood() {
        return Instant.now();
    }

    @Override
    public String getPath() {
        return "/keikai/v1";
    }
}
