package leigh.esp.tokei;

import leigh.eo.EO;
import leigh.eo.json.JsonOutput;
import leigh.esp.keikai.sdk.KeikaiClient;
import leigh.mecha.fabric.HandlerStatus;
import leigh.mecha.http.server.PrefixedHandler;
import leigh.mecha.http.server.WebTransaction;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.io.OutputStream;
import java.time.Instant;
import java.util.Set;

public class TokeiService extends PrefixedHandler {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(TokeiService.class);

    public TokeiService(Set<String> pathPrefixes) {
        super(pathPrefixes);

        KeikaiClient client = new KeikaiClient("http://localhost:8123",
                "/tokei",
                "http://localhost:8124/tokei");
        new Thread(client).start();
    }

    @Override
    public HandlerStatus handlePrefixedWebRequest(WebTransaction request) throws Throwable {
        request.httpServletResponse.setContentType("esp/fst");
        OutputStream os = request.httpServletResponse.getOutputStream();
        EO reply = new EO();
        reply.setValue("time", Instant.now());
        JsonOutput out = new JsonOutput(request.httpServletResponse.getOutputStream());
        out.writeEO(reply);
        out.close();
        return HandlerStatus.BREAK;
    }
}
