import { EF_INTERACTIVE } from "../../../EF_INTERACTIVE.js";
import { EF_RENDERING } from "../../../EF_RENDERING.js";
import { manageMediaBuffer } from "../shared/BufferUtils.js";
import { getLatestMediaEngine } from "../tasks/makeMediaEngineTask.js";
import { Task } from "@lit/task";
const makeAudioBufferTask = (host) => {
	let currentState = {
		currentSeekTimeMs: 0,
		requestedSegments: /* @__PURE__ */ new Set(),
		activeRequests: /* @__PURE__ */ new Set(),
		requestQueue: []
	};
	return new Task(host, {
		autoRun: EF_INTERACTIVE && !EF_RENDERING(),
		args: () => [host.desiredSeekTimeMs],
		onError: (error) => {
			console.error("audioBufferTask error", error);
		},
		onComplete: (value) => {
			currentState = value;
		},
		task: async ([seekTimeMs], { signal }) => {
			if (EF_RENDERING()) return currentState;
			const currentConfig = {
				bufferDurationMs: host.audioBufferDurationMs,
				maxParallelFetches: host.maxAudioBufferFetches,
				enableBuffering: host.enableAudioBuffering
			};
			return manageMediaBuffer(seekTimeMs, currentConfig, currentState, host.intrinsicDurationMs || 1e4, signal, {
				computeSegmentId: async (timeMs, rendition) => {
					const mediaEngine = await getLatestMediaEngine(host, signal);
					return mediaEngine.computeSegmentId(timeMs, rendition);
				},
				prefetchSegment: async (segmentId, rendition) => {
					const mediaEngine = await getLatestMediaEngine(host, signal);
					await mediaEngine.fetchMediaSegment(segmentId, rendition);
				},
				isSegmentCached: (segmentId, rendition) => {
					const mediaEngine = host.mediaEngineTask.value;
					if (!mediaEngine) return false;
					return mediaEngine.isSegmentCached(segmentId, rendition);
				},
				getRendition: async () => {
					const mediaEngine = await getLatestMediaEngine(host, signal);
					const audioRendition = mediaEngine.audioRendition;
					if (!audioRendition) throw new Error("Audio rendition not available");
					return audioRendition;
				},
				logError: console.error
			});
		}
	});
};
export { makeAudioBufferTask };
