/** 同時間只允許一個 WHEP 擷圖，並限制首頁總次數，避免拖慢頁面 */
const MAX_WHEP_CAPTURES_PER_SESSION = 4
const GAP_BETWEEN_CAPTURES_MS = 600

let tail: Promise<void> = Promise.resolve()
let whepCaptureCount = 0

export function canEnqueueWhepSnapshot(): boolean {
    return whepCaptureCount < MAX_WHEP_CAPTURES_PER_SESSION
}

export function enqueueSnapshotCapture<T>(task: () => Promise<T>): Promise<T> {
    const run = tail
        .then(() => new Promise<void>((resolve) => window.setTimeout(resolve, GAP_BETWEEN_CAPTURES_MS)))
        .then(async () => {
            if (!canEnqueueWhepSnapshot()) {
                return undefined as T
            }
            whepCaptureCount += 1
            try {
                return await task()
            } finally {
                // count 不遞減，整頁生命週期內上限
            }
        })

    tail = run.then(
        () => undefined,
        () => undefined
    )
    return run
}
