import { findAndUnblock } from "./checker/findAndUnblock.js";

import type { FindAndUnblockOptions } from "./checker/findAndUnblock.js";
import type { VisualConfiguration } from "./visual/createVisual.js";

/**
 * Use this class as main entry for your unblocking mechanism.
 *
 * **Attention:** Please make sure you start the watcher at time where the `document.readyState`
 * is not already `complete`. Why? At this time, we can make sure that our `jQuery.fn.ready` and
 * other initiators works as expected.
 */
class UnblockWatcher<ExtendedBlockerDefinition extends VisualConfiguration = VisualConfiguration> {
    private nextTimeout: ReturnType<typeof setTimeout>;

    private startTimeout: ReturnType<typeof setTimeout>;

    private options: FindAndUnblockOptions<ExtendedBlockerDefinition>;

    public constructor(options: FindAndUnblockOptions<ExtendedBlockerDefinition>) {
        this.options = options;
    }

    public unblockNow() {
        return findAndUnblock(this.options);
    }

    public start(mode: UnblockWatcher["options"]["mode"] = "unblock") {
        this.setMode(mode);
        this.stop();
        this.startTimeout = setTimeout(this.doTimeout.bind(this), 0);
    }

    private doTimeout() {
        clearTimeout(this.nextTimeout);
        this.unblockNow();
        this.nextTimeout = setTimeout(this.doTimeout.bind(this), 1000);
    }

    public stop() {
        clearTimeout(this.nextTimeout);
        clearTimeout(this.startTimeout);
    }

    public setMode(mode: UnblockWatcher["options"]["mode"]) {
        this.options.mode = mode;
    }
}

export { UnblockWatcher };
