package web;

import io.javalin.Javalin;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import static io.javalin.apibuilder.ApiBuilder.*;

public class webApp {
    private final Javalin app;
    private final String listenAddress;
    private final int listenPort;
    private final Logger logger = LoggerFactory.getLogger(webApp.class);
    private final Map<String, String> usermap = new HashMap<>();
    public webApp(String listenAddress, int listenPort, Pair<String, String>... users) {
        this.listenAddress = listenAddress;
        this.listenPort = listenPort;
        if (users != null){
            for (Pair<String, String> user : users) {
                this.usermap.put(user.getKey(), user.getValue());
            }
        }
        app = Javalin.create(config -> {
            config.useVirtualThreads = true; // Enable virtual threads for better performance
            config.staticFiles.add("/");
            config.router.apiBuilder(()->{
                path("/", () -> get(ctx -> {
                    if (ctx.sessionAttribute("user") == null) {
                        ctx.redirect("/index.html");
                    } else {
                        ctx.redirect("/pocreceiver.html");
                    }
                }));
                path("/index.html", ()-> {
                    before( ctx ->{
                        ctx.sessionAttribute("user", null); // Clear user session on index page
                    });
                    post(ctx-> {
                        var username = ctx.formParam("username");
                        var password = ctx.formParam("password");
                        var xx = usermap.get(username);
                        if (xx != null && xx.equals(password)) {
                            ctx.sessionAttribute("user", username);
                            ctx.redirect("/pocreceiver.html");
                        } else {
                            ctx.result("Invalid username or password");
                        }
                    });
                });
                path("/pocreceiver.html", ()->{
                    before(ctx -> {
                        if (ctx.sessionAttribute("user") == null) {
                            ctx.redirect("/index.html");
                        }
                    });
                    ws("/ws", wshandler -> wshandler.onMessage(wsMessageContext -> {
                        // Handle incoming WebSocket messages
                        String message = wsMessageContext.message();
                        // Process the message as needed
                    }));
                });
                path("/prerecordedbroadcast.html", ()->{
                    before(ctx -> {
                        if (ctx.sessionAttribute("user") == null) {
                            ctx.redirect("/index.html");
                        }
                    });
                    ws("/ws", wshandler -> wshandler.onMessage(wsMessageContext -> {
                        // Handle incoming WebSocket messages
                        String message = wsMessageContext.message();
                        // Process the message as needed
                    }));
                });
               path("/setting.html", () ->{
                    before(ctx -> {
                        if (ctx.sessionAttribute("user") == null) {
                            ctx.redirect("/index.html");
                        }
                    });
                   ws("/ws", wshandler -> wshandler.onMessage(wsMessageContext -> {
                       // Handle incoming WebSocket messages
                       String message = wsMessageContext.message();
                       // Process the message as needed
                   }));
                });

            });
        });

    }

    /**
     * Start the web application.
     */
    public boolean Start(){
        try{
            app.start(listenAddress, listenPort);
            return true;
        } catch (Exception e){
            logger.error("webApp start failed", e.getMessage());
        }
        return false;

    }

    /**
     * Stop the web application.
     */
    public void Stop(){
        try{
            app.stop();
            logger.info("webApp stopped");
        } catch (Exception e){
            logger.error("webApp stop failed", e.getMessage());
        }

    }
}
