import { ScrubInputCache } from "./ScrubInputCache.js";
import { Task } from "@lit/task";
const scrubInputCache = new ScrubInputCache();
const makeScrubVideoSeekTask = (host) => {
	return new Task(host, {
		args: () => [host.desiredSeekTimeMs],
		onError: (error) => {
			console.error("scrubVideoSeekTask error", error);
		},
		onComplete: (_value) => {},
		task: async ([desiredSeekTimeMs], { signal }) => {
			signal.throwIfAborted();
			const mediaEngine = host.mediaEngineTask.value;
			if (!mediaEngine) return void 0;
			const scrubRendition = mediaEngine.getScrubVideoRendition();
			if (!scrubRendition) return void 0;
			const scrubRenditionWithSrc = {
				...scrubRendition,
				src: mediaEngine.src
			};
			const segmentId = mediaEngine.computeSegmentId(desiredSeekTimeMs, scrubRenditionWithSrc);
			if (segmentId === void 0) return void 0;
			const isCached = mediaEngine.isSegmentCached(segmentId, scrubRenditionWithSrc);
			if (!isCached) return void 0;
			signal.throwIfAborted();
			try {
				const scrubInput = await scrubInputCache.getOrCreateInput(segmentId, async () => {
					const [initSegment, mediaSegment] = await Promise.all([mediaEngine.fetchInitSegment(scrubRenditionWithSrc, signal), mediaEngine.fetchMediaSegment(segmentId, scrubRenditionWithSrc)]);
					if (!initSegment || !mediaSegment || signal.aborted) return void 0;
					const { BufferedSeekingInput } = await import("../BufferedSeekingInput.js");
					const { EFMedia } = await import("../../EFMedia.js");
					return new BufferedSeekingInput(await new Blob([initSegment, mediaSegment]).arrayBuffer(), {
						videoBufferSize: EFMedia.VIDEO_SAMPLE_BUFFER_SIZE,
						audioBufferSize: EFMedia.AUDIO_SAMPLE_BUFFER_SIZE,
						startTimeOffsetMs: scrubRendition.startTimeOffsetMs
					});
				});
				if (!scrubInput) return void 0;
				const videoTrack = await scrubInput.getFirstVideoTrack();
				if (!videoTrack) return void 0;
				signal.throwIfAborted();
				const sample = await scrubInput.seek(videoTrack.id, desiredSeekTimeMs);
				return sample;
			} catch (error) {
				if (signal.aborted) return void 0;
				console.warn("Failed to get scrub video sample:", error);
				return void 0;
			}
		}
	});
};
export { makeScrubVideoSeekTask };
