
(() => {
    class Title
    {
        #stack = [];
        pushTitle(title) {
            this.#stack.push(title);
            this.#setTitle(title);
        }
        replaceTitle(title) {
            this.#stack.pop();
            this.pushTitle(title);
        }
        pop() {
            this.#stack.pop();
            this.#setTitle(this.#stack[this.#stack.length-1]);
        }

        #setTitle(title) {
            document.title = title ? `Photochamber - ${title}` : "Photochamber";
        }
    }
    document.Title = new Title();
})();

$(() => {
    function loadHash(md5sum) {
        if (md5sum && md5sum.length)
            LoadingTasks.push(async () => displayMediaFullPage(await MediaStorage.Instance.getMedia(md5sum)));
        else
            document.getElementById("pch-fullPageMedia").classList.add("hidden");
    }

    window.addEventListener("hashchange", x => {
        x.preventDefault();
        loadHash(document.location?.hash?.substr(1))
        return true;
    });

    onScrollBottom = (function () {
        this.lastCall= null;
        this.fnc = () => {
            if (this.lastCall !== null)
                return;
            this.lastCall = setTimeout(() => {
                this.lastCall = null;
            }, 1000);
            window.displayMoreMedia();
        };
        return this;
    })();

    window.addEventListener("scroll", evt => {
        if (window.scrollY+window.innerHeight >= document.body.clientHeight)
            onScrollBottom.fnc();
    });

    window.reloadServerDb = () => {
        $.ajax({
            url: "/api/database/reload",
            type: "POST",
            data: "{}"
        });
    }

    document.Title.pop();
    AccessManager.RebuildAccess();
    loadHash(document.location?.hash?.substr(1));
    MediaStorage.Instance.restoreMetaList();
});

