import {WebSocketPayload} from "../WebSocketPayload";
import {Modal} from "./Modal";
import {WebSocketEvent} from "../WebSocketEvent";
import {RequestType} from "../RequestType";
import {IJob} from "../database/IJob";
import {WebWebSocketHandler} from "./WebWebSocketHandler";
import {IDrink} from "../database/IDrink";
import {ButtonType} from "./ButtonType";

export class Fill {
    static onFillEvent(payload: WebSocketPayload) {
        let modal = new Modal("fill", "Cocktail wird zubereitet");
        let header = document.createElement("h2");
        header.innerText = "";

        modal.addContent(header);

        let txt = document.createElement("p");
        txt.innerHTML = ``;
        txt.id = "main_fillTxt";

        let waterAnimDiv = document.createElement("div");
        waterAnimDiv.classList.add("water");
        modal.addContent(txt);

        modal.addContent(waterAnimDiv);

        let seconds = document.createElement("span");
        seconds.innerText = "60s";
        seconds.style.marginRight = "3%";

        modal.addContent(seconds);

        let ml = document.createElement("span");
        ml.innerText = "200ml";
        modal.addContent(ml);

        modal.addContent(document.createElement("br"));
        modal.addContent(document.createElement("br"));


        let cancelBtn = document.createElement("button");
        cancelBtn.classList.add("btn", "btn-danger");
        cancelBtn.innerText = "STOP";
        cancelBtn.disabled = true;
        setTimeout(() => {
            cancelBtn.disabled = false;
        }, 1000);
        cancelBtn.onclick = () => {
            cancelBtn.disabled = true;
            txt.innerHTML = "Der Vorgang wird abgebrochen...";
            waterAnimDiv.classList.add("waterCancel");

            WebWebSocketHandler.send(new WebSocketPayload(WebSocketEvent.CANCEL));
        };
        modal.addContent(cancelBtn);

        function riseSlowlyUp(lastNumber: number, number: number) {
            for (let i = lastNumber; i < number; i++) {
                setTimeout(() => {
                    ml.innerText = Math.ceil(i) + "ml";
                }, (number - lastNumber / 1000) + i * 4);
            }
        }

        let interval;
        modal.open().then(() => {
            WebWebSocketHandler.request(RequestType.JOB).then((payload) => {
                let minus = -1;
                let job = payload.data as IJob;
                ml.innerText = "0ml";
                waterAnimDiv.style.setProperty("--fillTime", job.estimatedTime + "s");
                waterAnimDiv.style.backgroundImage = `url("/images/${job.drink._id}.png")`;
                txt.innerText = job.completeAmount + "ml";
                header.innerText = job.drink.name;
                seconds.innerText = Math.floor(job.estimatedTime) + "s";

                let last = 0;

                function updateTimeAndMl() {
                    minus++;
                    if (minus + 1 > (job.estimatedTime as number)) {
                        clearInterval(interval);
                    }

                    let iT = (Math.floor(job.estimatedTime as number - minus));
                    if (iT < 0)
                        iT = 0;
                    let eA = Math.floor((job.completeAmount / job.estimatedTime) * minus);
                    if (eA < 0) {

                        eA = 0;
                    }

                    seconds.innerText = iT + "s";
                    riseSlowlyUp(last, eA)
                    last = eA;
                }
                interval = setInterval(updateTimeAndMl, 1000);
                updateTimeAndMl();


                setTimeout(() => {
                    txt.innerHTML = "Bitte entnehme den Cocktail";
                    modal.title.innerHTML = "Cocktail fertig gestellt"
                    ml.innerText = job.completeAmount + "ml";

                    cancelBtn.classList.add("btn-blendout");
                    waterAnimDiv.classList.add("waterFinished");
                    cancelBtn.onclick = () => {
                        modal.close();
                    }
                }, job.estimatedTime * 1000);
            });
        });
    }

    static userFillRequest(drink: IDrink) {
        return new Promise<void>(async resolve => {
            let modal = new Modal("fillOptions", drink.name + " Mixen");
            let pre = document.createElement("p");
            pre.innerHTML = `Bitte wähle die Größe deines Glases aus<br>`;
            modal.addContent(pre);

            let div = document.createElement("div");
            div.style.display = "grid";
            div.style.minHeight = "20vh";
            div.style.gridTemplateRows = "100%";
            div.style.gridTemplateColumns = "repeat(4,auto)";
            div.style.marginTop = "5%";
            div.style.height = "50vh";
            div.style.marginBottom = "-12%";

            let sizes = [["shot", "Shot", 20], ["small", "Klein", 120], ["normal", "Normal", 200], ["large", "Groß", 300]];
            for (let s of sizes) {
                let glass = document.createElement("div");
                /*glass.style.maxWidth = "50%"
                glass.style.minWidth = "50%";*/
                let img = document.createElement("img");
                img.src = "/static/" + s[0] + ".png";
                img.style.minHeight = "50%";
                img.style.maxHeight = "50%";

                img.alt = "" + s[1];

                let bottom = document.createElement("p");
                bottom.style.textAlign = "center";
                bottom.innerHTML = `${s[1]} <span style="color:grey">${s[2]}ml</span>`;

                glass.append(img, bottom);
                div.append(glass);

                glass.onclick = () => {

                    WebWebSocketHandler.request(RequestType.STARTFILL, {drink: drink, amount: s[2]}).then((payload) => {
                        let data = payload.data as { success: boolean, job?: IJob };

                        if (!data.success) {
                            let modal = new Modal("fill", "Oh nein!");
                            let txt = document.createElement("p");
                            txt.innerHTML = `Es ist nicht genug Inhalt in den Behältern, um das gewünschte Getränk in der Größe bereitzustellen.<br><br>Bitte wende dich an das Wartungspersonal.<br><br>`;
                            modal.addContent(txt);
                            modal.addButton(ButtonType.SECONDARY, "Schließen", () => modal.close());
                            modal.open();
                        }
                    });
                };
            }
            modal.addContent(div);

            modal.addBR();
            modal.addButton(ButtonType.SECONDARY, "Abbrechen", () => modal.close());
            // modal.addButton(ButtonType.SUCCESS, "Starten", () => {});
            await modal.open();
            resolve();
        });
    }
}