import { Task } from "@lit/task";

import { EFMedia } from "../../EFMedia";
import type { EFVideo } from "../../EFVideo";
import { BufferedSeekingInput } from "../BufferedSeekingInput";
import type { InputTask } from "../shared/MediaTaskUtils";

export const makeVideoInputTask = (host: EFVideo): InputTask => {
  return new Task<
    readonly [ArrayBuffer | undefined, ArrayBuffer | undefined],
    BufferedSeekingInput
  >(host, {
    args: () =>
      [
        host.videoInitSegmentFetchTask.value,
        host.videoSegmentFetchTask.value,
      ] as const,
    onError: (error) => {
      console.error("videoInputTask error", error);
    },
    onComplete: (_value) => {},
    task: async () => {
      const initSegment = await host.videoInitSegmentFetchTask.taskComplete;
      const segment = await host.videoSegmentFetchTask.taskComplete;
      if (!initSegment || !segment) {
        throw new Error("Init segment or segment is not available");
      }

      // Get startTimeOffsetMs from the video rendition if available
      const mediaEngine = await host.mediaEngineTask.taskComplete;
      const videoRendition = mediaEngine?.videoRendition;
      const startTimeOffsetMs = videoRendition?.startTimeOffsetMs;

      const input = new BufferedSeekingInput(
        await new Blob([initSegment, segment]).arrayBuffer(),
        {
          videoBufferSize: EFMedia.VIDEO_SAMPLE_BUFFER_SIZE,
          audioBufferSize: EFMedia.AUDIO_SAMPLE_BUFFER_SIZE,
          startTimeOffsetMs,
        },
      );
      return input;
    },
  });
};
