import { EF_INTERACTIVE } from "../../../EF_INTERACTIVE.js";
import { EF_RENDERING } from "../../../EF_RENDERING.js";
import { manageMediaBuffer } from "../shared/BufferUtils.js";
import { getLatestMediaEngine, getVideoRendition } from "../tasks/makeMediaEngineTask.js";
import { Task } from "@lit/task";
const makeVideoBufferTask = (host) => {
	let currentState = {
		currentSeekTimeMs: 0,
		requestedSegments: /* @__PURE__ */ new Set(),
		activeRequests: /* @__PURE__ */ new Set(),
		requestQueue: []
	};
	return new Task(host, {
		autoRun: EF_INTERACTIVE,
		args: () => [host.desiredSeekTimeMs],
		onError: (error) => {
			console.error("videoBufferTask error", error);
		},
		onComplete: (value) => {
			currentState = value;
		},
		task: async ([seekTimeMs], { signal }) => {
			if (EF_RENDERING()) return currentState;
			const mediaEngine = await getLatestMediaEngine(host, signal);
			const engineConfig = mediaEngine.getBufferConfig();
			const bufferDurationMs = engineConfig.videoBufferDurationMs;
			const maxParallelFetches = engineConfig.maxVideoBufferFetches;
			const currentConfig = {
				bufferDurationMs,
				maxParallelFetches,
				enableBuffering: host.enableVideoBuffering
			};
			return manageMediaBuffer(seekTimeMs, currentConfig, currentState, host.intrinsicDurationMs || 1e4, signal, {
				computeSegmentId: async (timeMs, rendition) => {
					const mediaEngine$1 = await getLatestMediaEngine(host, signal);
					return mediaEngine$1.computeSegmentId(timeMs, rendition);
				},
				prefetchSegment: async (segmentId, rendition) => {
					const mediaEngine$1 = await getLatestMediaEngine(host, signal);
					await mediaEngine$1.fetchMediaSegment(segmentId, rendition);
				},
				isSegmentCached: (segmentId, rendition) => {
					const mediaEngine$1 = host.mediaEngineTask.value;
					if (!mediaEngine$1) return false;
					return mediaEngine$1.isSegmentCached(segmentId, rendition);
				},
				getRendition: async () => {
					const mediaEngine$1 = await getLatestMediaEngine(host, signal);
					return getVideoRendition(mediaEngine$1);
				},
				logError: console.error
			});
		}
	});
};
export { makeVideoBufferTask };
