package lc.ris.svc;

import lc.eo.EOBsonId;
import lc.eo.EOClient;
import lc.eo.json.EOJsonSerializer;
import lc.eo.sdk.EO;
import lc.mecha.fabric.HandlerStatus;
import lc.mecha.http.server.HttpTransaction;
import lc.mecha.http.server.PrefixedHandler;

import java.nio.charset.StandardCharsets;
import java.util.Set;

public class TagReadHandler extends PrefixedHandler {
    private final EOClient client;

    public TagReadHandler(EOClient client, Set<String> pathPrefixes) {
        super(pathPrefixes);
        this.client = client;
    }

    @Override
    public HandlerStatus handlePrefixedWebRequest(HttpTransaction request) throws Throwable {
        String lcit = request.httpServletRequest.getParameter("lcit");

        try (var txn = client.getTransaction("ris_test")) {
            EO obj = txn.objGet(new EOBsonId(lcit));
            if (obj == null) {
                request.httpServletResponse.setStatus(404);
                return HandlerStatus.BREAK;
            }
            request.httpServletResponse.getOutputStream().write(EOJsonSerializer.toJson(obj).toString().getBytes(StandardCharsets.UTF_8));
        }

        return HandlerStatus.BREAK;
    }
}
