import type { EngineMode } from './ffmpeg.types';
import { FFMPEG_CORE_BUILD_ID } from '../version';

export function resolveFromAppBase(
  relativePath: string,
  locationHref = window.location.href,
  viteBase = import.meta.env.BASE_URL
): string {
  const appBase = new URL(viteBase, locationHref);
  return new URL(relativePath, appBase).href;
}

export interface CoreAssetUrls {
  coreURL: string;
  wasmURL: string;
  workerURL?: string;
}

export function getCoreAssetUrls(
  mode: EngineMode,
  resolver: (path: string) => string = resolveFromAppBase
): CoreAssetUrls {
  const directory =
    mode === 'multithread'
      ? `vendor/ffmpeg/${FFMPEG_CORE_BUILD_ID}/mt/`
      : `vendor/ffmpeg/${FFMPEG_CORE_BUILD_ID}/st/`;
  const base = resolver(directory);
  const urls: CoreAssetUrls = {
    coreURL: new URL('ffmpeg-core.js', base).href,
    wasmURL: new URL('ffmpeg-core.wasm', base).href,
  };
  if (mode === 'multithread') {
    urls.workerURL = new URL('ffmpeg-core.worker.js', base).href;
  }
  return urls;
}
