import {Modal} from "./Modal";
import {WebWebSocketHandler} from "./WebWebSocketHandler";
import {IContainer} from "../database/IContainer";
import {IIngredient} from "../database/IIngredient";
import {ButtonType} from "./ButtonType";
import {RequestType} from "../RequestType";
import {WebSocketPayload} from "../WebSocketPayload";
import {WebSocketEvent} from "../WebSocketEvent";

export class Containers {

    /**
     * Open the menu for the container ingredient setup
     */
    static openMenu() {
        let modal = new Modal("containers", "Behälter aktualisieren");
        let txt = document.createElement("p");
        txt.innerText = "Zu aktualisierenden Behälter wählen";
        modal.addContent(txt);
        modal.addContent(document.createElement("br"));

        let form = document.createElement("div");
        modal.addContent(form);

        let btnSave = document.createElement("button");
        btnSave.innerText = "Speichern";
        btnSave.classList.add("btn", "btn-success")
        btnSave.disabled = true;

        let containerVolumes: Record<any, number> = {};
        let containers: Record<string, IContainer> = {};

        let volume = document.createElement("span");
        volume.innerText = "";
        volume.id = "containers_volume";




        let volumeSlider = document.createElement("input");
        volumeSlider.type = "range";
        volumeSlider.step = "5";
        volumeSlider.min = "0"
        volumeSlider.max = "2000";
        volumeSlider.classList.add("hidden");
        volumeSlider.id = "containers_volumeSlider"

        // When volume slider is changed
        function onChange() {
            volume.innerText = volumeSlider.value + " ml ";
            txt.innerText = "Speichern zum abschließen"
        }

        volumeSlider.oninput = onChange;
        volumeSlider.onchange = onChange;

        let volumeTemplates = document.createElement("div");
        volumeTemplates.id = "containers_templates";
        volumeTemplates.classList.add("hidden");
        let templates = [330, 500, 750, 1000, 1250, 1500];
        for (let t of templates) {
            let btn = document.createElement("button");
            btn.classList.add("btn", "btn-secondary");
            let v = t + "ml";
            if (t >= 1000)
                v = t / 1000 + "L";
            btn.innerText = v;
            btn.onclick = () => {
                volumeSlider.value = String(t);
                let event = new Event("change", {bubbles: true});
                volumeSlider.dispatchEvent(event);
            }
            volumeTemplates.append(btn);
        }

        let nonSelect = document.createElement("option");
        nonSelect.value = "-1";
        nonSelect.innerText = "Bitte wählen";
        nonSelect.disabled = true;


        let selectIngredient = document.createElement("select");
        selectIngredient.classList.add("hidden");
        selectIngredient.classList.add("input");
        selectIngredient.style.width = "35%"

        // When ingredient is changed
        selectIngredient.onchange = () => {
            if (selectIngredient.value == "null") {
                volumeSlider.value = "0";
                volumeSlider.disabled = true;
            } else {
                volumeSlider.disabled = false;
            }

            volumeSlider.classList.remove("hidden");
            volumeTemplates.classList.remove("hidden");
            volume.innerText = volumeSlider.value + " ml ";

            if (selectContainer.value && selectIngredient.value)
                btnSave.disabled = false;


            txt.innerText = "Menge des Inhalts mittels Slider einstellen";
        }
        let noIngredient = document.createElement("option");
        noIngredient.value = "null";
        noIngredient.innerText = "Kein Inhalt";
        selectIngredient.append(noIngredient);
        selectIngredient.selectedIndex = 0;

        let selectContainer = document.createElement("select");
        selectContainer.classList.add("input");
        //let containers : IContainer[] = [];
        selectContainer.onchange = () => {
            // Enable select ingredient field and set max and min to the slider
            selectIngredient.classList.remove("hidden");
            volumeSlider.max = String(2000);
            volumeSlider.min = String(0);
            volumeSlider.value = String(containerVolumes[selectContainer.value]);
            volume.innerText = String(containerVolumes[selectContainer.value]);
            txt.innerText = "Inhalt des Behälters auswählen";

            // When content of container is filled, preselect the ingredient selector
            if (containers[selectContainer.value] && containers[selectContainer.value].content) {
                selectIngredient.value = containers[selectContainer.value].content?._id;
                let event = new Event('change', {bubbles: true});
                selectIngredient.dispatchEvent(event);
            }


        }


        selectContainer.append(nonSelect.cloneNode(true));
        selectContainer.selectedIndex = 0;


        WebWebSocketHandler.request(RequestType.CONTAINERS).then((payload) => {
            for (let container of (payload.data as IContainer[])) {
                containerVolumes[container._id] = container.volume;
                let option = document.createElement("option");
                option.value = container._id;
                option.innerText = "Behälter Slot " + (container.slot + 1) + "[" + (container.content && container.content.name ? container.content.name : "Kein Inhalt") + "]";
                selectContainer.append(option);
                containers[container._id] = container;
            }
            //containers = payload.data as IContainer[];
        });
        WebWebSocketHandler.request(RequestType.INGREDIENTS).then((payload) => {
            for (let ingredient of (payload.data as IIngredient[])) {
                let option = document.createElement("option");
                option.value = ingredient._id;
                option.innerText = ingredient.name;
                selectIngredient.append(option);
            }
        });

        form.append(selectContainer, document.createElement("br"), selectIngredient, document.createElement("br"), volumeTemplates, volume, volumeSlider);


        modal.addContent(document.createElement("br"));
        modal.addButton(ButtonType.DANGER, "Abbrechen", () => modal.close());


        modal.addContent(btnSave);

        btnSave.onclick = () => {

            // Validation
            if (selectIngredient.value == "-1" || selectContainer.value == "-1") {
                return;
            }

            // If no ingredient, move slider to 0
            if (selectIngredient.value == "null")
                volumeSlider.value = "0";

            let payload = new WebSocketPayload(WebSocketEvent.CONTAINER_UPDATE, {
                container: selectContainer.value,
                ingredient: (selectIngredient.value == "null") ? null : selectIngredient.value,
                filled: volumeSlider.value
            });

            WebWebSocketHandler.send(payload).then(() => {
                selectContainer.value = "-1";
                selectIngredient.value = "-1";
                let event = new Event('change', {bubbles: true});
                selectContainer.dispatchEvent(event);
                selectIngredient.dispatchEvent(event);
            });
            modal.close();
        };

        modal.open();
    }
}