import { LOCAL_STORAGE_KEY_QUEUE_NOTIFY_WORKER_PREFIX } from "./notifyWorkerTab.js";
import { localStorageTest } from "../../utils/localStorageTest.js";
import { getStaticOptions } from "../../utils/options.js";

import type { WorkerTabNotification } from "./notifyWorkerTab.js";

/**
 * Check existing worker notifications and execute a given callback.
 */
function checkWorkerNotifications(callbacks: Record<string, (data?: any) => void>) {
    if (localStorageTest()) {
        const lsPrefix = `${LOCAL_STORAGE_KEY_QUEUE_NOTIFY_WORKER_PREFIX}${getStaticOptions().localStorageSuffix}`;
        for (const lsEntryName of Object.keys(localStorage)) {
            if (lsEntryName.startsWith(lsPrefix)) {
                const { event, data } = JSON.parse(localStorage.getItem(lsEntryName)) as WorkerTabNotification;
                localStorage.removeItem(lsEntryName);
                callbacks[event]?.(data);
            }
        }

        return true;
    }
    return false;
}

export { checkWorkerNotifications };
