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

    async loadPresents() {
        this.presents = require("./presents").default;
        await this.updateStates();
    }

    async updateStates() {
        //TODO vom server laden
        this.presents[3].isBought = true;
    }

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

        await this.loadPresents();

        presentContainer.innerText = "";
        console.log(this.presents);
        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: { isBought: boolean; image: string; name: string; description: string; link: string }, isBought: boolean) {
        //TODO auf Server updaten
        present.isBought = isBought;
    }
}