"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = VideoRetry;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = tslib_1.__importStar(require("react"));
const __1 = require("../..");
function VideoRetry(props) {
    const retryTimeoutRef = (0, react_1.useRef)(null);
    const [retries, setRetries] = (0, react_1.useState)(0);
    const playing = (0, __1.usePlayerStore)((x) => x.status === __1.PlayerStatus.PLAYING);
    const mode = (0, __1.usePlayerStore)((x) => x.mode);
    const status = (0, __1.usePlayerStore)((x) => x.status);
    const [lastChange, setLastChange] = (0, react_1.useState)(Date.now());
    const [tick, setTick] = (0, react_1.useState)(0);
    (0, react_1.useEffect)(() => {
        setLastChange(Date.now());
    }, [status]);
    (0, react_1.useEffect)(() => {
        if (mode === "vod")
            return;
        if (!playing) {
            const handle = setInterval(() => {
                setTick(Date.now());
            }, 1000);
            return () => clearInterval(handle);
        }
    }, [setTick, playing]);
    const stalledFor5sec = !playing && tick - lastChange > 5000;
    (0, react_1.useEffect)(() => {
        if (stalledFor5sec) {
            console.log("Stalled for 5 seconds, retrying...");
            setRetries((r) => r + 1);
        }
    }, [stalledFor5sec]);
    (0, react_1.useEffect)(() => {
        if (mode === "vod")
            return;
        if (!playing && status !== __1.PlayerStatus.PAUSE) {
            const doRetry = () => {
                console.log("Retrying video playback...");
                setRetries((prevRetries) => prevRetries + 1);
            };
            const jitter = 2000 + Math.random() * 1500;
            retryTimeoutRef.current = setTimeout(doRetry, jitter);
        }
        return () => {
            if (retryTimeoutRef.current) {
                console.log("Clearing retry timeout");
                clearTimeout(retryTimeoutRef.current);
                retryTimeoutRef.current = null;
            }
        };
    }, [!playing, mode, status]);
    return (0, jsx_runtime_1.jsx)(react_1.default.Fragment, { children: props.children }, retries);
}
//# sourceMappingURL=video-retry.js.map