package leigh.esp.eko;

import leigh.eo.EO;
import leigh.eo.json.JsonInput;
import leigh.esp.kabe.Service;
import leigh.mecha.http.server.WebTransaction;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;

/**
 * EKO implements a simple echo service which is useful for testing end-to-end throughput and latency.
 *
 * @author Alex Leigh
 */
public class EkoService implements Service {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(EkoService.class);

    @Override
    public void handleClientRequest(WebTransaction clientRequest) throws IOException {
        try {
            JsonInput foi = new JsonInput(clientRequest.httpServletRequest.getInputStream());
            EO request = foi.readEo();

            Integer replyBytes = request.getValueInteger("replyBytes");
            if (replyBytes != null && replyBytes > 0) {
                clientRequest.httpServletResponse.setContentType("text/plain");
                // We presume this is already buffered.
                OutputStream os = clientRequest.httpServletResponse.getOutputStream();
                for (int i = 0; i < replyBytes; i++) {
                    os.write('A');
                }
            }
        } catch (IOException 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 "/eko/v1";
    }
}
