"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextMatchTimer = void 0;
const config_js_1 = require("../config.js");
const CONTEXT_MATCH_TIMEOUT_MAX = (0, config_js_1.numberConfig)('CONTEXT_MATCH_TIMEOUT_MAX', 3 * 60000);
const CONTEXT_MATCH_TIMEOUT_LOADED = (0, config_js_1.numberConfig)('CONTEXT_MATCH_TIMEOUT_LOADED', 60000);
const CONTEXT_MATCH_TIMEOUT_IDLE = (0, config_js_1.numberConfig)('CONTEXT_MATCH_TIMEOUT_IDLE', 15000);
class ContextMatchTimer {
    constructor(config, page) {
        this.config = config;
        this.page = page;
        this.wasLoaded = false;
        this.wasIdle = false;
        this.maxTimeoutAt = Date.now() + config.get(CONTEXT_MATCH_TIMEOUT_MAX);
        this.currentTimeoutAt = this.maxTimeoutAt;
    }
    checkExpired() {
        const loaded = this.page.target.loaded;
        const networkIdle = [...this.page.browser.attachedPages()].every(p => p.networkManager.isSilent());
        const idle = loaded && networkIdle;
        if (!this.wasLoaded && loaded) {
            this.wasLoaded = true;
            this.adjustTimeout(this.config.get(CONTEXT_MATCH_TIMEOUT_LOADED));
        }
        if (!this.wasIdle && idle) {
            this.wasIdle = true;
            this.adjustTimeout(this.config.get(CONTEXT_MATCH_TIMEOUT_IDLE));
        }
        if (!loaded) {
            this.wasLoaded = false;
            this.wasIdle = false;
            this.adjustTimeout(this.config.get(CONTEXT_MATCH_TIMEOUT_MAX));
        }
        return Date.now() > this.currentTimeoutAt;
    }
    adjustTimeout(newTimeout) {
        this.currentTimeoutAt = Math.min(Date.now() + newTimeout, this.maxTimeoutAt);
    }
}
exports.ContextMatchTimer = ContextMatchTimer;
//# sourceMappingURL=context-match-timer.js.map