import {UserAction, UserSite} from "../../../../../js/lib/pwa-user-management";
import {Helper, InitPromise} from "../../../../../js/lib/pwa-lib";
import {DataManager} from "../../../../../js/lib/pwa-core";

export class DeleteWordsSite extends UserSite {
    constructor(siteManager) {
        super(siteManager, "version/2/html/deleteLevels.html", null, "admin");
    }

    async onConstruct(args) {
        let res = super.onConstruct(args);
        this.words = (await DataManager.load("getDoubleUsedWordsAction"))["result"];
        return res;
    }


    onFirstStart() {
        super.onFirstStart();

        let levelTemplate = this.findBy("#level-template");
        let wordTemplate = this.findBy("#word-template");
        let wordContainer = this.findBy("#word-container");

        levelTemplate.id = null;
        levelTemplate.remove();

        wordTemplate.id = null;
        wordTemplate.remove();

        for (let k in this.words) {
            let wordElem = Helper.cloneNode(wordTemplate);
            wordElem.querySelector(".name").appendChild(document.createTextNode(k));
            let levelContainer = wordElem.querySelector(".level-container");
            for (let j = 0; j < this.words[k].length; j++) {
                let level = this.words[k][j];
                let levelElem = Helper.cloneNode(levelTemplate);
                levelElem.querySelector(".id").appendChild(document.createTextNode(level["id"]));
                levelElem.querySelector(".words").appendChild(document.createTextNode(level["words"]));
                levelElem.querySelector(".positions").appendChild(document.createTextNode(level["rotations"]));

                levelElem.querySelector(".delete-button").addEventListener("click", async () => {
                    let res = await DataManager.send("deleteLevel", {"levelId": level["id"]});
                    if (res["success"]){
                        levelElem.remove();
                    }
                });

                levelContainer.appendChild(levelElem);
            }
            wordContainer.appendChild(wordElem);
        }
    }
}

InitPromise.addPromise(app => {
    app.addDefaultAction(new UserAction("delete-levels", () => {
        app.startSite(DeleteWordsSite);
    },null, null, "admin"))
});