import {supportWebp, webpQuery} from "./checkwebp.ts";
import {Howl} from "howler";
import {loadSvga} from "@grace/svgaplayer";


export const svgaRegex = (/\.(svga)$/);
export const jpgRegex = (/\.(jpe?g)$/);
export const pngRegex = (/\.(png)$/);
export const webpRegex = (/\.(webp)$/);
export const gifRegex = (/\.(gif)$/);

export const imgRegex = (/\.(png|jpe?g|webp|gif)$/);

const typeRegex = (/\.([^.]+)$/);

const loaders = {
  ".jpg": loadImg,
  ".jpeg": loadImg,
  ".png": loadImg,
  ".webp": loadImg,
  ".gif": loadImg,

  // svga
  '.svga': loadSvga,

  // 音乐
  '.mp3': loadAudio,
}

export async function preload(
  urls: string[],
  onProcess?: (progress: number, loaded: number, total: number) => void,
  onComplete?: () => void
) {
  const ps = [];

  let loaded = 0;
  const total = urls.length;

  // 获取文件类型
  urls.forEach((url) => {

    const type = url.match(typeRegex)?.[0];

    const loadFunc = loaders[type] || loadUnknown;

    const p = loadFunc(url).then(() => {
      loaded++;
      const progress = loaded / total;
      onProcess && onProcess(progress, loaded, total);
      if (loaded >= total) {
        onComplete && onComplete();
      }
    });

    ps.push(p);

  });

}

/**
 * 加载一张图片
 * @param {string} url 地址
 */
export function loadImg(url: string) {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = err => {
      console.warn('load', url, err);
      resolve(null);
    };
    img.crossOrigin = 'anonymous';
    img.src = url + (supportWebp() ? webpQuery : '');
  });
}

// export function loadSvga(url: string) {
//   return Promise.resolve();
// }


const audioCache: { [key in string]: Howl } = {};

export async function loadAudio(src: string) {

  if (!audioCache[src]) {
    audioCache[src] = await new Promise((resolve) => {
      let sound = new Howl({
        src,
        preload: true,
        onload: () => {
          resolve(sound);
        },
        onloaderror: () => {
          resolve(null);
        },
      });
    });
  }

  return audioCache[src];
}


export function loadUnknown(url: string) {
  console.warn(`load unknown: ${url}`);
  return Promise.resolve();
}
