import { supportWebp, webpQuery } from "./checkwebp.ts";


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': loadSvga,
}

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();
}

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