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

const LOCAL_STORAGE_KEY_LOCK_TAB = "real-queue-lock-tab";

let keepUpToDateInterval: ReturnType<typeof setInterval>;

/**
 * Lock this tab as "current runner". This allows you to run the queue only in one tab.
 *
 * @return `true` when the current tab is locked and should not process any jobs
 */
function lockTab(state?: boolean) {
    if (localStorageTest()) {
        const lsKey = `${LOCAL_STORAGE_KEY_LOCK_TAB}-${getStaticOptions().localStorageSuffix}`;

        if (typeof state === "boolean") {
            clearInterval(keepUpToDateInterval);
        }

        if (state === true) {
            const fnWrite = () => localStorage.setItem(lsKey, new Date().getTime().toString());
            fnWrite();
            keepUpToDateInterval = setInterval(fnWrite, 3000);
        } else if (state === false) {
            localStorage.removeItem(lsKey);
        }

        const currentValue = +localStorage.getItem(lsKey);
        if (currentValue === 0 || isNaN(currentValue)) {
            return false;
        }

        return new Date().getTime() - currentValue < 7000;
    }

    return false;
}

export { LOCAL_STORAGE_KEY_LOCK_TAB, lockTab };
