import { fetchStatus } from "./fetchStatus.js";
import { createJobToPopulateNextJobs } from "./job/jobToPopulateNextJobs.js";
import { notifyWorkerTab } from "./tabBridge/notifyWorkerTab.js";

let currentlyFetching = false;

/**
 * Refresh the queue and load new, unlocked jobs. You need to call this function in your
 * code if you know, there are new jobs added (e.g. "Scan complete site" button).
 */
async function refreshQueue(doFetchStatus = true) {
    if (currentlyFetching) {
        // There is still a request, skip this
        return;
    }

    // Check, if the current worker is locked
    if (window.realQueueWorker) {
        currentlyFetching = true;
        try {
            await createJobToPopulateNextJobs(0)();
            doFetchStatus && fetchStatus(true);
        } finally {
            currentlyFetching = false;
        }
    } else {
        // Let the other tab know that it should refresh the queue
        notifyWorkerTab({
            event: "refreshQueue",
        });
    }
}

export { refreshQueue };
