import {WordRotatorBaseSite} from "./WordRotatorBaseSite";
import {LevelSite} from "./LevelSite";
import {Matomo, ScaleHelper, SoundManager} from "../../../../../js/lib/pwa-assets";
import {TemplateContainer} from "../wordrotator/Segment/TemplateContainer";
import {MainMenuLevel} from "../wordrotator/Level/MainMenuLevel";
import {FlashMessenger, Helper, InitPromise, ShareManager} from "../../../../../js/lib/pwa-lib";
import {DataManager, SettingsManager} from "../../../../../js/lib/pwa-core";
import {WordRotatorDb} from "../WordRotatorDb";
import {ShareDialog} from "../dialog/ShareDialog";

export class MenuSite extends WordRotatorBaseSite {
    constructor(siteManager) {
        super(siteManager, "html/application/menu.html");
        this.loadLevelPromise = this.loadLevels();
        this.listener = null;
    }

    onStart(args) {
        Matomo.update("Menu Site");
        let res = super.onStart(args);

        let level = new MainMenuLevel(this.templateContainer);
        level.setWords(["WORD", "ROTA", "TORW", "ORDR"]);
        level.createSegments();

        level.getWonPromise().then(() => {
            Matomo.push(["trackEvent", "MainMenu", "levelSolved"]);
            this.startLevelSite();
        });

        let segment = level.getRootSegment();
        segment._updateElement();

        let levelSegment = this.findBy("#level");
        levelSegment.removeAllChildren().appendChild(segment.getElement());

        let rotationsSegments = level.getRotatableSegments();

        let randomRotationFunction = () => {
            let timeout = Math.random() * 4500 + 1500;
            this.randomRotateTimeout = setTimeout(() => {
                let indexBlocked = -1;
                let indexesNotRight = [];
                for (let i = 0; i < rotationsSegments.length; i++) {
                    if (rotationsSegments[i].rotation !== 0) {
                        indexesNotRight.push(i);
                        if (indexesNotRight.length >= 2) {
                            break;
                        }
                    }
                }
                if (indexesNotRight.length === 1) {
                    indexBlocked = indexesNotRight[0];
                }

                let index = Math.floor(Math.random() * rotationsSegments.length);
                if (index === indexBlocked) {
                    index = (index + 1) % rotationsSegments.length;
                }

                rotationsSegments[index].rotate();
                randomRotationFunction();
            }, timeout);
        };
        randomRotationFunction();

        this.listener = async () => {
            let playButton = this.findBy("#play-button");
            let levelNumber = this.findBy("#level-number");
            levelNumber.innerText = Helper.nonNull(localStorage.getItem("levelCounter"), 1);

            let levelSegment = this.findBy("#level");

            let scaleHelper = new ScaleHelper();
            await scaleHelper.scaleToFull(levelSegment, levelSegment.parentElement, false, false, 2, 8, null, false);

            // debugger;
            let levelStyle = getComputedStyle(levelSegment);
            playButton.style.width = levelStyle.getPropertyValue("width");
            scaleHelper.scaleToFull(playButton.children[0], playButton, null, null, null, 4, null, false);

            await scaleHelper.scaleTo(0.2, levelNumber.parentElement, levelNumber.parentElement.parentElement, null, null, null, 10, null, false);
            scaleHelper.scaleToFull(levelNumber, levelNumber.parentElement, false, false, 8, null, null, false);
        };

        this.listener();
        window.addEventListener("resize", this.listener);

        //Musikbuttons update, falls in den Einstellungen umgestellt
        let settingsManager = SettingsManager.getInstance();
        let playSoundButton = this.findBy("#play-sound");
        playSoundButton.checked = (settingsManager.getSetting("play-sound", "1") === "1");
        let playMusicButton = this.findBy("#play-music");
        playMusicButton.checked = (settingsManager.getSetting("play-music", "1") === "1");

        return res;
    }

    async startLevelSite() {
        SoundManager.getInstance().resumeContext();
        this.startSite(LevelSite, Promise.race([this.loadLevelPromise, new Promise(async resolve => {
            const db = WordRotatorDb.getInstance();
            let level = await db.loadNextLevel(LevelSite.RENDERER_TYPES);
            if (level !== null) {
                resolve();
            }
        })]));
    }

    async onFirstStart() {
        super.onFirstStart();

        let playButton = this.findBy("#play-button");
        playButton.addEventListener("click", () => {
            Matomo.push(["trackEvent", "MainMenu", "startButton"]);
            this.startLevelSite();
        });

        let leafSegmentTemplate = this.findBy("#segment-leaf-template");
        let parentSegmentTemplate = this.findBy("#segment-parent-template");
        let rowSegmentTemplate = this.findBy("#segment-row-template");
        let triangleTemplate = this.findBy("#segment-triangle-template");

        leafSegmentTemplate.id = null;
        parentSegmentTemplate.id = null;
        rowSegmentTemplate.id = null;
        triangleTemplate.id = null;

        leafSegmentTemplate.remove();
        parentSegmentTemplate.remove();
        rowSegmentTemplate.remove();
        triangleTemplate.remove();

        this.templateContainer = new TemplateContainer(leafSegmentTemplate, parentSegmentTemplate, rowSegmentTemplate, triangleTemplate);

        if (Helper.nonNull(MenuSite.app._cookieClosePromise)) {
            MenuSite.app._cookieClosePromise.then(() => {
                if (this.listener) {
                    this.listener();
                }
            });
        }

        let settingsManager = SettingsManager.getInstance();
        let soundManager = SoundManager.getInstance();

        let playMusicButton = this.findBy("#play-music");
        playMusicButton.checked = (settingsManager.getSetting("play-music", "1") === "1");
        playMusicButton.addEventListener("change", () => {
            settingsManager.setSetting("play-music", (playMusicButton.checked)?"1":"0");
            soundManager.set({muted: !playMusicButton.checked}, SoundManager.CHANNELS.MUSIC);
            if (playMusicButton.checked) {
                soundManager.play(SoundManager.CHANNELS.MUSIC);
            }
            Matomo.push(["trackEvent", "MainMenu", "PlayMusic", "Play Music", (playMusicButton.checked) ? 1 : 0]);
        });

        let playSoundButton = this.findBy("#play-sound");
        playSoundButton.checked = (settingsManager.getSetting("play-sound", "1") === "1");
        playSoundButton.addEventListener("change", () => {
            settingsManager.setSetting("play-sound", (playSoundButton.checked)?"1":"0");
            soundManager.set({muted: !playSoundButton.checked}, SoundManager.CHANNELS.SOUND);
            Matomo.push(["trackEvent", "MainMenu", "PlaySound", "Play Sound", (playSoundButton.checked) ? 1 : 0]);
        });

        this.findBy("#share-button").addEventListener("click", () => {
            new ShareDialog().show();
        });
        // this.findBy("#share-buttons").appendChild(ShareManager.generateDefaultShareElement("https://wordrotator.silas.link"));
    }

    onPause(args) {
        clearTimeout(this.randomRotateTimeout);
        window.removeEventListener("resize", this.listener);
        super.onPause(args);
    }

    async loadLevels() {
        const dateLastSync = Helper.nonNull(localStorage.getItem("date-last-sync"), 0);
        const db = WordRotatorDb.getInstance();

        // let numberLevels = db.countLevels();
        let newLastSync = null;
        let maxRuns = 1;
        let levelPromises = [];
        for (let run = 0; run < maxRuns; run++) {
            let res = await DataManager.load("wordRotator/levels" + DataManager.buildQuery({
                "currentRun": run,
                "dateLastSync": dateLastSync
            }));
            if (!res["success"]) {
                if (await db.loadNextLevel(LevelSite.RENDERER_TYPES) === null) {
                    FlashMessenger.addMessage("sync-error", null, 6000);
                }
                newLastSync = null;
                break;
            }
            res = res["result"];
            newLastSync = Helper.nonNull(newLastSync, res["currentSyncDate"]);
            maxRuns = res["maxRuns"];

            let levels = res["levels"];
            for (let i = 0; i < levels.length; i++) {
                let currentLevel = levels[i];
                levelPromises.push(db.loadLevel(levels[i]["id"]).then(level => {
                    currentLevel["played"] = (Helper.nonNull(Helper.nonNull(level, {}).played, false));
                    return currentLevel;
                }));
            }
        }
        let levels = await Promise.all(levelPromises);
        console.log("levels to save", levels);
        await db.saveManyLevels(levels);

        if (newLastSync != null && newLastSync !== "null") {
            localStorage.setItem("date-last-sync", newLastSync);
        }
    }
}

MenuSite.app = null;
InitPromise.addPromise(app => {
    MenuSite.app = app;
});