export class PresentsHandler {
    presents: {
        [id: number]: {
            id: number,
            version: number,
            isBought: boolean,
            image: string,
            name: string,
            description: string
            link: string
        }
    } = {};

    // @ts-ignore
    private readonly basePath = __BASE_PATH__;

    async loadPresents() {
        const presents = require("./presents").default;
        presents.forEach(p => this.presents[p.id] = p);
        await this.updateStates();
    }

    async updateStates() {
        const presentData: any[] = await fetch(this.basePath + "/presents", {
            "credentials": "same-origin",
            "method": "GET",
        }).then(function (res) {
            return res.json();
        });

        presentData.forEach(data => {
            const present = this.presents[data.id];
            if (present){
                present.isBought = data.isBought === 1;
                present.version = data.version;
            }
        })
    }

    async showPresents() {
        const presentContainer = document.getElementById("present-container");
        const presentTemplate = document.getElementById("present-template");
        presentTemplate.remove();
        presentTemplate.removeAttribute("id");

        await this.loadPresents();

        presentContainer.innerText = "";
        Object.values(this.presents).forEach(present => {
            const element = <HTMLLinkElement>presentTemplate.cloneNode(true);
            (<HTMLImageElement>element.querySelector(".present-image")).src = present.image;
            (<HTMLElement>element.querySelector(".present-name")).innerText = present.name;
            (<HTMLElement>element.querySelector(".present-description")).innerText = present.description;
            element.href = present.link;

            const checkboxElement = element.querySelector(".present-checkbox");
            if (present.isBought) {
                checkboxElement.classList.add("checked");
            }

            checkboxElement.addEventListener("click", async e => {
                e.preventDefault();
                await this.setPresentIsBought(present, !present.isBought);
                if (present.isBought) {
                    checkboxElement.classList.add("checked");
                } else {
                    checkboxElement.classList.remove("checked");
                }
            })

            presentContainer.appendChild(element);
        })
    }

    private async setPresentIsBought(present: { id: number, isBought: boolean; version: number, image: string; name: string; description: string; link: string }, isBought: boolean) {
        const url = this.basePath + "/presents"

        const params = {
            id: present.id,
            version: present.version,
            isBought: isBought
        }

        const res = await this.send(url, params);

        console.log("result", res);

        if (res.present && res.present.id === present.id) {
            present.version = res.present.version;
            present.isBought = res.present.isBought === 1
        }

        if (res.success === false) {
            if (res.error === "wrong-version") {
                alert("Jemand hat schon vor dir das Geschenk bearbeitet. Bitte versuche es erneut.")
            }
        }
    }

    private async send(url, params) {
        let headers = {};
        if (!(params instanceof FormData) && typeof params === "object") {
            params = JSON.stringify(params);
            headers = {
                "Content-Type": "application/json"
            }
        }

        return fetch(url, {
            "credentials": "same-origin",
            "method": "POST",
            "headers": headers,
            "body": params,
        }).then(function (res) {
            return res.json();
        }).catch(function (e) {
            debugger;
            console.error("error", e);
            return {
                "success": false,
                "errors": [
                    "not-online"
                ]
            }
        });
    }
}