import {Modal} from "./Modal";
import {WebSocketEvent} from "../WebSocketEvent";
import {WebSocketPayload} from "../WebSocketPayload";
import {ButtonType} from "./ButtonType";
import {iTenderStatus} from "../iTenderStatus";
import {WebHandler} from "./WebHandler";
import {Setup} from "./Setup";
import {Pane} from "./Pane";
import {RequestType} from "../RequestType";
import {Fill} from "./Fill";
import {Settings} from "./Settings";

export class WebWebSocketHandler {
    private static socket: WebSocket;
    private static url = (window.location.protocol == "http:" ? "ws://" : "wss://") + window.location.hostname + ":3005";
    private static eventRegister: { event: WebSocketEvent, fn: (payload: WebSocketPayload) => void }[] = [];


    constructor(resolver: (() => void)) {
        WebWebSocketHandler.socket = new WebSocket(WebWebSocketHandler.url);
        WebWebSocketHandler.socket.onopen = (x) => {
            resolver();
            this.onOpen(x);
        };
        WebWebSocketHandler.socket.onclose = this.onClose;
        WebWebSocketHandler.socket.onerror = this.onError;
        WebWebSocketHandler.socket.onmessage = this.onMessage;

    }

    public static registerForEvent(event: WebSocketEvent, fn: (payload: WebSocketPayload) => void) {
        for (let e of WebWebSocketHandler.eventRegister) {
            if (e.fn == fn) {
                console.log("Event fn already registered");
                return;
            }
        }

        WebWebSocketHandler.eventRegister.push({event: event, fn: fn});
    }

    /**
     * @return Promise<WebSocketPayload>
     * @param type
     * @param content
     */
    public static request(type: RequestType, content: any = null): Promise<WebSocketPayload> {
        console.log("Request to " + type)
        return new Promise(resolve => {
            WebWebSocketHandler.registerForEvent(WebSocketEvent.RESPONSE, (payload) => {
                if ((payload.data["type"] as RequestType) == type) {
                    resolve(payload.data);
                }
            });
            WebWebSocketHandler.send(new WebSocketPayload(WebSocketEvent.REQUEST, {
                type: type,
                data: content
            }));
        });
    }

    public static send(payload: WebSocketPayload): Promise<void> {
        console.log("[WS] Sending " + payload.event + " Event", payload);
        return new Promise(async (resolve, reject) => {
            try {
                if (this.socket && this.socket.readyState == 1) {
                    await this.socket.send(payload.toString());
                    resolve();
                }
            } catch (e) {
                /*let modal = new Modal("error", "Verbindungsfehler");
                let txt = document.createElement("p");
                txt.innerHTML = `Beim Austausch von Informationen ist ein Problem aufgetreten.<br>Falls dies öfter passieren sollte, ist der Support zu kontaktieren.`;
                modal.addContent(txt);
                await modal.open();*/
                reject();
            }
        });
    }

    private static checkConnection(): Promise<boolean> {
        return new Promise(async resolve => {
            const xhr = new XMLHttpRequest();
            xhr.open("GET", '/status', true);

            //Send the proper header information along with the request
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            xhr.onreadystatechange = () => { // Call a function when the state changes.
                if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                    resolve(true);
                } else if (xhr.readyState == XMLHttpRequest.DONE) {
                    resolve(false);
                }
            }

            try {
                await xhr.send();
            } catch (e) {
                resolve(false);
            }

        })
    }

    private onMessage(msgEvent: MessageEvent) {
        let payload = WebSocketPayload.parseFromBase64Json(msgEvent.data);
        if (!payload) {
            console.log("[WS] Could not parse message: ", msgEvent);
            return;
        }
        console.log("[WS] Received " + payload.event + " Event", payload);

        for (let evReg of WebWebSocketHandler.eventRegister) {
            if (evReg.event == payload.event)
                evReg.fn(payload);
        }

        switch (payload.event) {
            case WebSocketEvent.CONFIG: {
                Setup.onConfigUpdate(payload);
                break;
            }

            case WebSocketEvent.DRINKS: {
                WebHandler.onDrinkUpdate(payload);
                break;
            }

            case WebSocketEvent.ERROR: {
                let modal = new Modal("error", "Aww crap!");
                let txt = document.createElement("p");
                txt.innerHTML = payload.data;
                modal.addContent(txt);
                modal.addContent(document.createElement("br"));
                modal.addButton(ButtonType.SECONDARY, "Schließen", () => modal.close());
                modal.open();
                Settings.inUpdate = false;
                break;
            }

            // Incoming WebSocketStatus
            case WebSocketEvent.STATUS: {
                let statusElement = document.getElementById("status");
                if (statusElement)
                    statusElement.innerText = payload.data.status;

                let status: iTenderStatus = payload.data.status;

                switch (status) {
                    case iTenderStatus.READY: {
                        Modal.close("start");
                        Modal.close("setup");
                        Modal.close("fill");
                        Modal.close("download");
                        if (WebHandler.currentPane != Pane.MENU)
                            WebHandler.openPane(Pane.MAIN);
                        (document.getElementById("menuBtn") as HTMLButtonElement).disabled = false;
                        break;
                    }
                    case iTenderStatus.STARTING: {
                        let modal = new Modal("start", "Willkommen!");
                        let txt = document.createElement("p");
                        txt.innerHTML = `Einen Augenblick bitte<br>iTender startet...`;
                        modal.addContent(txt);
                        modal.loader = true;
                        modal.open();
                        break;
                    }
                    case iTenderStatus.DOWNLOADING: {
                        let modal = new Modal("download", "Aktualisieren");
                        let txt = document.createElement("p");
                        txt.innerHTML = `Einen Augenblick bitte<br>iTender synchronisiert die Datenbank mit der Cloud...`;
                        modal.addContent(txt);
                        modal.loader = true;
                        modal.open();
                        setTimeout(() => {
                            if (txt) {
                                txt.innerHTML = txt.innerHTML + "<br><br>Der Vorgang dauert länger als gewöhnlich.<br>Überprüfe deine Internetverbindung!"
                            }
                        }, 1000 * 15)
                        break;
                    }
                    case iTenderStatus.SETUP: {
                        Modal.close("start");
                        Setup.openSetup();
                        break;
                    }
                    case iTenderStatus.FILLING: {
                        Fill.onFillEvent(payload);
                        break;
                    }
                    default: {
                        console.log("Unknown to handle " + status);
                    }
                }
                break;
            }

        }
    }

    private onOpen(event) {
        console.log("[WS] Connected", event);

        const blockPanel = document.getElementById("blockPanel") as HTMLDivElement;
        blockPanel.classList.add("opacityOutDisplayNone");
    }

    private onClose(event) {
        console.error("[WS] Closed!", event);
        if (event.wasClean) {
            let modal = new Modal("socketClosed", "Sitzung beendet!");
            let txt = document.createElement("p");
            txt.innerHTML = `Diese Sitzung wurde beendet, da der iTender nun an einem anderen Gerät bzw. an dem Hauptgerät gesteuert wird.<br><br>`;
            modal.addContent(txt);
            modal.addButton(ButtonType.PRIMARY, "Sitzung wiederherstellen", () => {
                window.location.reload();
            });
            modal.open();
        } else {
            setInterval(async () => {
                if ((await WebWebSocketHandler.checkConnection()))
                    window.location.reload();
            }, 2000);

            if (Settings.inUpdate)
                return;

            let modal = new Modal("socketClosed", "Verbindungsproblem!");
            let txt = document.createElement("p");
            txt.innerHTML = `Die Benutzeroberfläche hat die Verbindung mit dem Gerät verloren.<br>Die Verbindung wird wiederhergestellt...<br>`;
            modal.addContent(txt);
            modal.loader = true;
            modal.open();
        }

        /* let connectionElement = document.getElementById("right");
         if (connectionElement) {
             connectionElement.innerText = "Getrennt";
             connectionElement.style.color = "red";
         }*/
    }

    private onError(event) {
        console.error("[WS] Error", event);
        /*let connectionElement = document.getElementById("right");
        if (connectionElement)
            connectionElement.innerText = "Fehler";*/
        //openModal("Einen Augenblick...", `Es wurde ein kritischer Fehler festgestellt.\nBitte warten Sie, während der Prozess neu gestartet wird...` );
        //window.location.reload();
    }


}