package cz.moneta.test.harness.connectors.wso2;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import cz.moneta.test.harness.connectors.common.ServletConfigAccessor;
import cz.moneta.test.harness.connectors.rest.RemoteRestCallRequest;
import cz.moneta.test.harness.connectors.rest.SimpleRestConnector;
import cz.moneta.test.harness.context.ConfigAccessor;
import org.apache.commons.lang3.tuple.Pair;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.GenericType;
import java.io.IOException;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class Wso2ConnectorServlet extends HttpServlet {

    private static final ObjectMapper JACKSON = new ObjectMapper()
            .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
            .registerModules(new ParameterNamesModule(), new Jdk8Module(), new JavaTimeModule());

    private final ConfigAccessor store;
    private final SimpleRestConnector connector;

    public Wso2ConnectorServlet() {
        this.store = new ServletConfigAccessor();
        this.connector = new SimpleRestConnector(
                store.getConfig("endpoints.wso2.url"), "Wso2ConnectorServlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        Optional.ofNullable(req.getPathInfo())
                .flatMap(pi -> Stream.<Supplier<Optional<Supplier<Pair<Integer, String>>>>>of(
                        () -> Optional.of(pi).filter(i -> i.contains("/call-get")).map(i -> () -> callGet(req)),
                        () -> Optional.of(pi).filter(i -> i.contains("/call-post")).map(i -> () -> callPost(req)))
                        .map(Supplier::get)
                        .filter(Optional::isPresent)
                        .map(Optional::get)
                        .findFirst())
                .map(Supplier::get)
                .ifPresent(r -> mapOntoResponse(r, resp));
    }

    private void mapOntoResponse(Pair<Integer, String> result, HttpServletResponse resp) {
        try {
            resp.setContentType("application/json");
            resp.setStatus(result.getLeft());
            resp.getWriter().write(result.getRight());
        } catch (IOException e) {
            e.printStackTrace();  //TODO logging
        }
    }

    private Pair<Integer, String> callGet(HttpServletRequest req) {
        try {
            RemoteRestCallRequest request = JACKSON.readValue(req.getInputStream(), RemoteRestCallRequest.class);
            return connector.get(
                    request.getPath(),
                    request.getGetProperties(),
                    new GenericType<>(String.class),
                    request.getHeaders());
        } catch (Exception e) {
            e.printStackTrace(); //TODO logging
            return null;
        }
    }

    private Pair<Integer, String> callPost(HttpServletRequest req) {
        try {
            RemoteRestCallRequest request = JACKSON.readValue(req.getInputStream(), RemoteRestCallRequest.class);
            return connector.post(
                    request.getPath(),
                    Entity.json(request.getRequest()),
                    new GenericType<>(String.class),
                    request.getHeaders());
        } catch (Exception e) {
            e.printStackTrace(); //TODO logging
            return null;
        }
    }

    @Override
    public void destroy() {
        connector.close();
    }
}
