"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useVideoFetch = useVideoFetch;
const react_1 = require("react");
const streamplace_store_1 = require("../streamplace-store");
const video_store_1 = require("../video-store");
// Fetches the place.stream.video metadata for the given AT-URI and pushes it
// into the surrounding VideoProvider's store. Refetches whenever the uri or
// the active agent changes. This is the VOD analogue of the livestream
// websocket consumer: instead of a long-lived socket, VOD metadata is a
// one-shot read that we hydrate into the store.
function useVideoFetch(aturi) {
    const store = (0, video_store_1.getVideoStoreFromContext)();
    const agent = (0, streamplace_store_1.usePossiblyUnauthedPDSAgent)();
    const abortRef = (0, react_1.useRef)(null);
    (0, react_1.useEffect)(() => {
        if (!agent || !aturi) {
            return;
        }
        // cancel any in-flight request from a previous uri/agent
        abortRef.current?.abort();
        const abort = new AbortController();
        abortRef.current = abort;
        const { setAturi, setVideo, setLoading, setError } = store.getState();
        setAturi(aturi);
        setLoading(true);
        setError(null);
        agent.place.stream.media
            .getVideo({ uri: aturi }, { signal: abort.signal })
            .then((res) => {
            if (abort.signal.aborted)
                return;
            setVideo(res.data);
            setLoading(false);
        })
            .catch((e) => {
            if (abort.signal.aborted)
                return;
            console.error("error fetching video", e);
            setError(e?.message ?? "failed to load video");
            setLoading(false);
        });
        return () => abort.abort();
    }, [agent, aturi, store]);
}
//# sourceMappingURL=fetch.js.map