package org.openautonomousconnection.webserver.runtime;

import org.openautonomousconnection.protocol.packets.v1_0_0.beta.WebRequestPacket;
import org.openautonomousconnection.protocol.packets.v1_0_0.beta.WebResponsePacket;
import org.openautonomousconnection.protocol.side.web.ConnectedWebClient;
import org.openautonomousconnection.protocol.side.web.ProtocolWebServer;
import org.openautonomousconnection.webserver.api.WebPage;
import org.openautonomousconnection.webserver.api.WebPageContext;

import java.io.File;

public final class JavaPageDispatcher {

    private static final JavaPageCache CACHE = new JavaPageCache();

    private JavaPageDispatcher() {}

    public static WebResponsePacket dispatch(
            ConnectedWebClient client,
            ProtocolWebServer server,
            WebRequestPacket request
    ) throws Exception {

        if (request.getPath() == null) return null;

        String p = request.getPath().startsWith("/") ? request.getPath().substring(1) : request.getPath();
        File javaFile = new File(server.getContentFolder(), p + ".java");

        if (!javaFile.exists() || !javaFile.isFile()) return null;

        Class<?> clazz = CACHE.getOrCompile(javaFile);
        Object instance = clazz.getDeclaredConstructor().newInstance();

        if (!(instance instanceof WebPage page))
            throw new IllegalStateException("Java page must implement WebPage");

        WebPageContext ctx = new WebPageContext(client, server, request);
        return page.handle(ctx);
    }
}
