import {LocalStorageSettingsFragment, SettingsManager, SettingsSite} from "../../../../../js/lib/pwa-core";
import {Dialog, FlashMessenger, Helper, InitPromise, ThemeManager, Translator} from "../../../../../js/lib/pwa-lib";
import {WordRotatorDb} from "../WordRotatorDb";
import {InstallManager, Matomo, MyStorageManager, SoundManager} from "../../../../../js/lib/pwa-assets";
import {CreditsSite} from "../site/CreditsSite";
import {PrivacyPolicySite} from "../site/PrivacyPolicySite";
import {ChooseThemeDialog} from "../dialog/ChooseThemeDialog";
import {ContactSite} from "../../../../../js/lib/pwa-contact";
import {ImpressumSite} from "../site/ImpressumSite";
import {PersistDialog} from "../dialog/PersistDialog";

export class WordRotatorSettingFragment extends LocalStorageSettingsFragment {
    constructor(site) {
        super(site, "html/application/fragment/settings.html");
    }

    onFirstStart() {
        let currentThemeName = ThemeManager.currentTheme._name;
        SettingsManager.getInstance().setSetting("theme", currentThemeName);

        let themeNameElem = this.findBy("#theme-name");
        themeNameElem.removeAllChildren().appendChild(Translator.makePersistentTranslation(currentThemeName));
        this.findBy("#theme-chooser").addEventListener("click", async () => {
            let newTheme = await (new ChooseThemeDialog()).show();
            if (Helper.isNotNull(newTheme)) {
                SettingsManager.getInstance().setSetting("theme", newTheme);
                ThemeManager.changeCurrentTheme(newTheme);
                themeNameElem.removeAllChildren().appendChild(Translator.makePersistentTranslation(newTheme));
            }
        });

        this.findBy("#reset-levels").addEventListener("click", () => {
            localStorage.removeItem("currentLevel");
            localStorage.removeItem("date-last-sync");
            localStorage.removeItem("levelCounter");
            localStorage.removeItem("tutorial-step");
            WordRotatorDb.getInstance().removeAll(WordRotatorDb.OBJECT_STORE.LEVEL);
        });

        if (location.hostname.includes("beta") || location.hostname.includes("127.0.0.1")) {
            this.findBy("#reset-levels").classList.remove("hidden");
        }

        let playMusicButton = this.findBy("#play-music");
        playMusicButton.addEventListener("change", () => {
            let soundManager = SoundManager.getInstance();
            soundManager.set({muted: !playMusicButton.checked}, SoundManager.CHANNELS.MUSIC);
            if (playMusicButton.checked) {
                soundManager.play(SoundManager.CHANNELS.MUSIC);
            }
        });

        this.findBy("#track-switch").addEventListener("change", function (e) {
            Matomo.setTrack(this.checked === true);
            e.stopPropagation();
            e.preventDefault();
        });

        this.findBy("#credits-button").addEventListener("click", () => {
            this.getSite().startSite(CreditsSite);
        });
        this.findBy("#privacy-policy-button").addEventListener("click", () => {
            this.getSite().startSite(PrivacyPolicySite);
        });
        this.findBy("#contact-button").addEventListener("click", () => {
            this.getSite().startSite(ContactSite);
        });
        this.findBy("#impressum-button").addEventListener("click", () => {
            this.getSite().startSite(ImpressumSite);
        });

        InstallManager.setCanInstallListener(() => {
            let installButton = this.findBy("#install-button");
            installButton.addEventListener("click", () => {
                installButton.classList.add("hidden");
                InstallManager.prompt().then((e) => {
                    console.log("clicked", e);
                    if (e["outcome"] === "accepted") {
                        Matomo.trackEvent("installed", "installed")
                    }
                });
            });
            installButton.classList.remove("hidden");
        });

        let storageManager = MyStorageManager.getInstance();
        if (storageManager.canPersist()) {
            Promise.all([storageManager.isPersistent(), navigator.serviceWorker["ready"]]).then(res => {
                let isPersisted = res[0];
                let storageObject = this.findBy("#storage-info");
                storageObject.appendChild(Translator.makePersistentTranslation("storage-info", [
                    ((isPersisted) ? "" : "nicht")]));
                storageObject.parentElement.classList.remove("hidden");
                storageObject.parentElement.addEventListener("click", async () => {
                    if (!isPersisted) {
                        let shouldAskForNotifications = false;
                        try {
                            // Helper.isChrome()
                            shouldAskForNotifications = await (new PersistDialog().show());
                            if (shouldAskForNotifications) {
                                if (Helper.isChrome()) {
                                    let sub = await res[1]["pushManager"]["subscribe"]({
                                        "userVisibleOnly": true,
                                        "applicationServerKey": new Uint8Array([4, 148, 221, 15, 14, 122, 35, 21, 93, 74, 222, 174, 235, 216, 129, 40, 51, 187, 105, 151, 5, 96, 178, 155, 61, 201, 78, 209, 176, 187, 145, 94, 98, 96, 95, 27, 59, 90, 162, 0, 12, 225, 59, 105, 99, 135, 208, 210, 69, 29, 148, 141, 4, 178, 66, 114, 80, 207, 22, 90, 0, 115, 60, 150, 217])
                                    });
                                }
                            }
                        } catch (e) {
                            if ('Notification' in window && Notification.permission === 'denied') {
                                FlashMessenger.addMessage('notification-permission-denied');
                            }
                        }
                        if (Helper.isChrome() || shouldAskForNotifications) {
                            isPersisted = await storageManager.persist();
                            storageObject.removeAllChildren().appendChild(Translator.makePersistentTranslation("storage-info", [
                                ((isPersisted) ? "" : "nicht")]));
                        }
                    }
                    else {
                        new Dialog("already-persited-dialog-message", "already-persited-dialog-title").show();
                    }
                    // storageManager.persist().then(isPersisted => {
                    //     storageObject.removeAllChildren().appendChild(Translator.makePersistentTranslation("storage-info", [
                    //         Math.round(storage.usage / (1024 * 1024) * 100) / 100,
                    //         Math.round(storage.quota / (1024 * 1024) * 100) / 100,
                    //         Math.round(storage.usage / storage.quota * 10000) / 100,
                    //         ((isPersisted) ? "" : "nicht")]));
                    //
                    //     console.log("p", isPersisted);
                    //     if (!isPersisted){
                    //         FlashMessenger.addMessage("storage-permission-not-get");
                    //     }
                    //     else {
                    //         FlashMessenger.addMessage("storage-permission-get");
                    //     }
                    // });
                })
            });
        }
        return super.onFirstStart();
    }

    onStart() {
        Matomo.update("Settings Site");
        super.onStart();
    }
}

InitPromise.addPromise(function () {
    SettingsSite.addSettingsFragment("settings", WordRotatorSettingFragment);
});