import {WebWebSocketHandler} from "./WebWebSocketHandler";
import {Modal} from "./Modal";
import {WebHandler} from "./WebHandler";
import {Pane} from "./Pane";
import {WebSocketPayload} from "../WebSocketPayload";
import {WebSocketEvent} from "../WebSocketEvent";
import {ButtonType} from "./ButtonType";
import {Containers} from "./Containers";
import {Setup} from "./Setup";
import {RequestType} from "../RequestType";
import {IContainer} from "../database/IContainer";
import {Settings} from "./Settings";

const main = document.getElementById("main");
const time = document.getElementById("right");

document.addEventListener("DOMContentLoaded", async () => {
    console.log("DOM Loaded");
    WebHandler.openPane(Pane.NONE);


    await connect();

    setupOnClickEvents();

    // Wait because sometimes the browser isn't ready for this dom update :(
    setTimeout(() => {
        WebWebSocketHandler.request(RequestType.CONTAINERS).then(Setup.onContainerUpdate);
    }, 1000);


    setInterval(() => {
        if (!time) return;

        let currentDate = new Date();
        time.innerText = "" + (currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours()) + ":" + (currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes());
    }, 1000);


    WebWebSocketHandler.registerForEvent(WebSocketEvent.CONTAINERS, (payload) => {
        let container: IContainer;
        let bottomContainers = document.getElementById("menuContainers") as HTMLDivElement;
        bottomContainers.innerHTML = "";
        let containers = payload.data as IContainer[];
        containers = containers.reverse();


        for (container of containers) {
            let containerDiv = document.createElement("div") as HTMLDivElement;
            containerDiv.classList.add("container");


            let span = document.createElement("span") as HTMLSpanElement;
            let pcnt = Math.round(container.filled * 100 / container.volume);
            if (!container.content)
                span.innerText = "-";
            else if (isNaN(pcnt))
                span.innerText = "?%";
            else
                span.innerText = pcnt + "%";

            if (pcnt < 5) {
                containerDiv.style.backgroundColor = "var(--danger)";
            } else if (pcnt < 15) {
                containerDiv.style.backgroundColor = "#EF4F00";
            } else if (pcnt < 40) {
                containerDiv.style.backgroundColor = "#FF5400";
            } else {
                containerDiv.style.backgroundColor = "#5B5B9B";
            }

            containerDiv.innerHTML = `<div class="tooltip">${span.innerText}
  <span class="tooltiptext">${container.content?.name} ${Math.ceil(container.filled)}ml</span>
</div>`;

            bottomContainers.append(containerDiv);
        }
    })
});

function setupOnClickEvents() {
    // Menu BTN
    const menuBtn = document.getElementById("menuBtn") as HTMLButtonElement;
    menuBtn.disabled = true;


    function doMenu() {
        if (WebHandler.currentPane != Pane.MENU) {
            WebHandler.openPane(Pane.MENU);
        } else {
            WebHandler.openPane(Pane.MAIN);
        }
    }

    menuBtn.onclick = doMenu;

    // Menu buttons
    const menuContainersBtn = document.getElementById("menu_containers") as HTMLButtonElement;
    const menuStatsBtn = document.getElementById("menu_stats") as HTMLButtonElement;

    menuContainersBtn.onclick = Containers.openMenu;


    menuStatsBtn.onclick = async () => {
        let modal = new Modal("stats", "Statistiken");

        let table = document.createElement("table");
        table.style.marginLeft = "auto";
        table.style.marginRight = "auto";

        let th = document.createElement("th");
        table.append(th);

        let tdTh1 = document.createElement("td");
        tdTh1.innerText = "";
        let tdTh2 = document.createElement("td");
        tdTh2.innerText = "";

        th.append(tdTh1, tdTh2);

        WebWebSocketHandler.request(RequestType.STATS).then((payload) => {
            let x = [["drinks_finished", "Ausgegebene Cocktails"], ["drink_most", "Beliebtester Cocktail"], ["count_cocktails", "Anzahl an Cocktails"], ["count_ingredients", "Anzahl an Zutaten"]];
            for (let y of x) {
                let tr = document.createElement("tr");
                let td1 = document.createElement("td");
                let td2 = document.createElement("td");

                td1.innerText = y[1];
                td1.style.fontWeight = "bold";
                td2.innerText = payload.data[y[0]];
                tr.append(td1, td2);

                table.append(tr);
            }
            modal.addContent(table);

            modal.addContent(document.createElement("br"));
            modal.addButton(ButtonType.SECONDARY, "Schließen", () => modal.close());
            modal.open();
        });

    };

    const menuSettingsBtn = document.getElementById("menu_settings") as HTMLButtonElement;
    const menuSetupBtn = document.getElementById("menu_setup") as HTMLButtonElement;

    menuSettingsBtn.onclick = () => WebHandler.openPane(Pane.SETTINGS);
    menuSetupBtn.onclick = () => {
        let payload = new WebSocketPayload(WebSocketEvent.SETUP, true);
        WebWebSocketHandler.send(payload);
    }


    Settings.addListeners();


}

let wsHandler;

function connect(): Promise<void> {
    return new Promise(resolve => {
        wsHandler = new WebWebSocketHandler(resolve);
    });

}
