import { Task } from "@lit/task";
import type { MediaEngine } from "../../../transcoding/types";
import type { EFVideo } from "../../EFVideo";
import { getLatestMediaEngine } from "../tasks/makeMediaEngineTask";

export const makeVideoSegmentFetchTask = (
  host: EFVideo,
): Task<
  readonly [MediaEngine | undefined, number | undefined],
  ArrayBuffer
> => {
  return new Task(host, {
    args: () =>
      [host.mediaEngineTask.value, host.videoSegmentIdTask.value] as const,
    onError: (error) => {
      console.error("videoSegmentFetchTask error", error);
    },
    onComplete: (_value) => {},
    task: async (_, { signal }) => {
      const mediaEngine = await getLatestMediaEngine(host, signal);
      const segmentId = await host.videoSegmentIdTask.taskComplete;
      if (segmentId === undefined) {
        // Provide more context in the error to help with debugging
        const rendition = mediaEngine.videoRendition;
        const debugInfo = {
          hasRendition: !!rendition,
          segmentDurationMs: rendition?.segmentDurationMs,
          segmentDurationsMs: rendition?.segmentDurationsMs?.length || 0,
          desiredSeekTimeMs: host.desiredSeekTimeMs,
          intrinsicDurationMs: host.intrinsicDurationMs,
        };
        throw new Error(
          `Segment ID is not available for video. Debug info: ${JSON.stringify(debugInfo)}`,
        );
      }
      return mediaEngine.fetchMediaSegment(
        segmentId,
        mediaEngine.getVideoRendition(),
        signal,
      );
    },
  });
};
