
$(() => {
    class AccessManager {
        #linkStoredAccesses = new Set();
        #isAdmin = false;

        constructor() {
            this.#linkStoredAccesses.clear();
            let linkStoredAccesses = [];
            try {
                linkStoredAccesses = (JSON.parse(localStorage?.getItem("accessLinks") || "[]") || []);
            } catch (err) {
                console.error(err);
            }
            linkStoredAccesses.forEach(i => this.#linkStoredAccesses.add(i));
        }

        #UpdateStorage() {
            let arr = Array.from(this.#linkStoredAccesses).reduce((acc, i) => { acc[i.key] = i; return acc; }, {});
            arr = Object.keys(arr).map(i => arr[i]);
            this.#linkStoredAccesses = new Set(arr);
            localStorage?.setItem("accessLinks", JSON.stringify(arr));
        }

        Logout(code) {
            let value = null;
            this.#linkStoredAccesses.forEach(i => {
                if (i.key === code) {
                    this.#linkStoredAccesses.delete(i);
                    value = i.value;
                }
            });
            if (!value)
                return;
            this.#UpdateStorage();
            return LoadingTasks.push(() => {
                return new Promise(ok => {
                    $.ajax({
                        url: `/api/access/${code}`,
                        type: "DELETE",
                        success: async data => {
                            window.ReloadAccessList(data);
                            await window.indexedData.removeAll();
                            await MediaStorage.Instance.rebuildMetaList();
                            ok();
                        },
                        error: err => ok(false),
                    });
                });
            });
        }

        IsAdmin() {
            return this.#isAdmin;
        }

        LinkLogin(linkList) {
            return new Promise(ok => {
                $.ajax({
                    url: "/api/access/link",
                    type: "POST",
                    data: { linkIds: JSON.stringify(Array.from(linkList)) },
                    success: async data => {
                        for (let i in data)
                            data[i].linkId && this.#linkStoredAccesses.add({key: i, value: data[i].linkId });
                        this.#isAdmin = data.isAdmin;
                        this.#UpdateStorage();
                        window.ReloadAccessList(data);
                        ok();
                    },
                    error: err => ok(false),
                });
            });
        }

        async RebuildAccess() {
            if (this.#linkStoredAccesses.size) {
                return LoadingTasks.push(() => {
                    return this.LinkLogin(Array.from(this.#linkStoredAccesses).map(x => x.value));
                });
            } else {
                return LoadingTasks.push(() => {
                    return new Promise(ok => {
                        $.get("/api/access/list", data => {
                            for (let i in data) {
                                data[i].linkId && this.#linkStoredAccesses.add({key: i, value: data[i].linkId });
                            }
                            this.#isAdmin = data.isAdmin;
                            this.#UpdateStorage();
                            window.ReloadAccessList(data);
                            MediaStorage.Instance.rebuildMetaList().finally(ok);
                        });
                    });
                });
            }
        }

    }

    window.AccessManager = new AccessManager();
});

