package Webpage;

import io.javalin.Javalin;
import io.javalin.http.staticfiles.Location;

import java.util.Objects;
import java.util.Properties;

import static code.common.*;

public class WebServer {
    private final Javalin app;
    private final int listenport;
    private final String webusername;
    private final String webpassword;
    public WebServer(Properties prop) {
        listenport = GetProperties_IntValue(prop,"WebListenPort", 8080);
        webusername = GetProperties_StringValue(prop,"WebUsername", "admin");
        webpassword = GetProperties_StringValue(prop,"WebPassword", "admin");

        app = Javalin.create(config -> config.addStaticFiles("/public", Location.CLASSPATH)).start(listenport);
        app.get("/", ctx ->{
           if (Objects.equals(ctx.sessionAttribute("username"), webusername)){
               ctx.redirect("/index.html");
           } else {
               ctx.sessionAttribute("username", null);
               ctx.redirect("/login.html");
           }
        });
        app.get("/logout", ctx -> {
            ctx.sessionAttribute("username", null);
            ctx.redirect("/login.html");
        });
        app.get("/setting", ctx -> {
            if (Objects.equals(ctx.sessionAttribute("username"), webusername)){
                //TODO Setting Page
                ctx.result("Setting Page");
            } else {
                ctx.redirect("/login.html");
            }
        });
        app.post("/login", ctx -> {
            String username = ctx.formParam("username");
            String password = ctx.formParam("password");
            if (Objects.equals(username, webusername) && Objects.equals(password, webpassword)){
                ctx.sessionAttribute("username", username);
                ctx.redirect("/index.html");
            } else {
                ctx.redirect("/login.html");
            }
        });
        app.post("/setting", ctx -> {
            if (Objects.equals(ctx.sessionAttribute("username"), webusername)){
                //TODO Setting Page
                ctx.result("Setting Page");
            } else {
                ctx.redirect("/login.html");
            }
        });
    }

    /**
     * Start the web server
     */
    public void Start(){
        if (app!=null) app.start(listenport);
    }

    /**
     * Stop the web server
     */
    public void Stop(){
        if (app!=null) app.stop();
    }
}
