"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSegmentTiming = useSegmentTiming;
const react_1 = require("react");
const livestream_store_1 = require("../livestream-store");
function getLiveConnectionQuality(timeBetweenSegments, range, numOfSegments = 1) {
    if (timeBetweenSegments === null || range === null)
        return "poor";
    if (timeBetweenSegments <= 1500 && range <= (1500 * 60) / numOfSegments) {
        return "good";
    }
    if (timeBetweenSegments <= 3000 && range <= (3000 * 60) / numOfSegments) {
        return "degraded";
    }
    return "poor";
}
function useSegmentTiming() {
    const latestSegment = (0, livestream_store_1.useLivestreamStore)((x) => x.segment);
    const [segmentDeltas, setSegmentDeltas] = (0, react_1.useState)([]);
    const prevSegmentRef = (0, react_1.useRef)(latestSegment);
    const prevTimestampRef = (0, react_1.useRef)(null);
    const ls = (0, livestream_store_1.useLivestream)();
    // Dummy state to force update every second
    const [, setNow] = (0, react_1.useState)(Date.now());
    (0, react_1.useEffect)(() => {
        const interval = setInterval(() => {
            setNow(Date.now());
        }, 1000);
        return () => clearInterval(interval);
    }, []);
    (0, react_1.useEffect)(() => {
        if (latestSegment && prevSegmentRef.current !== latestSegment) {
            const now = Date.now();
            if (prevTimestampRef.current !== null) {
                const delta = now - prevTimestampRef.current;
                // Only store the last 25 deltas
                setSegmentDeltas((prev) => [...prev, delta].slice(-25));
            }
            prevTimestampRef.current = now;
            prevSegmentRef.current = latestSegment;
        }
    }, [latestSegment]);
    // The most recent time between segments
    const timeBetweenSegments = segmentDeltas.length > 0
        ? segmentDeltas[segmentDeltas.length - 1]
        : prevTimestampRef.current
            ? Date.now() - prevTimestampRef.current
            : null;
    // Calculate mean and range of deltas
    const mean = segmentDeltas.length > 0
        ? Math.round(segmentDeltas.reduce((acc, curr) => acc + curr, 0) /
            segmentDeltas.length)
        : null;
    const range = segmentDeltas.length > 0
        ? Math.max(...segmentDeltas) - Math.min(...segmentDeltas)
        : null;
    let to_ret = {
        segmentDeltas,
        timeBetweenSegments,
        mean,
        range,
        connectionQuality: "poor",
    };
    to_ret.connectionQuality = getLiveConnectionQuality(timeBetweenSegments, range, segmentDeltas.length);
    if (!ls) {
        to_ret.connectionQuality = "pre-live";
    }
    return to_ret;
}
//# sourceMappingURL=useSegmentTiming.js.map