package lc.mecha.http.server;

import jakarta.servlet.Servlet;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.websocket.api.WebSocketListener;
import org.eclipse.jetty.websocket.server.JettyWebSocketServlet;
import org.eclipse.jetty.websocket.server.JettyWebSocketServletFactory;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;

/**
 * Dev/test implementation of a WebSocket.
 *
 * @author Alex Leigh
 */
public class WebsocketThing implements WebSocketListener {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(WebsocketThing.class);

    public static void main(String[] args) throws Exception {
        int serverPort = Integer.getInteger("server.port", 8123);

        Server server = new Server(serverPort);
        ContextHandlerCollection handlers = new ContextHandlerCollection();
        //  ResourceHandler rh = new ResourceHandler();
        // rh.setDirectoriesListed(false);
        //   rh.setBaseResource(Resource.newClassPathResource("/WEB-STATIC/"));
        //   handlers.addHandler(createContextHandler("/", rh));

        Servlet websocketServlet = new JettyWebSocketServlet() {
            @Override
            protected void configure(JettyWebSocketServletFactory factory) {
                factory.addMapping("/", (req, res) -> new WebsocketThing());
            }
        };

        ServletContextHandler servletContextHandler = new ServletContextHandler();
        servletContextHandler.addServlet(new ServletHolder(websocketServlet), "/ws");
        JettyWebSocketServletContainerInitializer.configure(servletContextHandler, null);
        handlers.addHandler(servletContextHandler);
        server.setHandler(handlers);
        server.start();
        server.join();
    }

    private static ContextHandler createContextHandler(String contextPath, Handler wrappedHandler) {
        ContextHandler ch = new ContextHandler(contextPath);
        ch.setHandler(wrappedHandler);
        ch.clearAliasChecks();
        ch.setAllowNullPathInfo(true);
        return ch;
    }

    public void onWebSocketText(String message) {
        logger.info("Received text. [str: {}]", message);
    }
}
