import { assetManager, ImageAsset, SpriteFrame, Texture2D } from "cc";

const loadCache = {};

assetManager.downloader.register('.svga', async (path, options, onComplete) => {

    // // @ts-ignore
    // assetManager.downloader.downloadFile(path, {responseType: 'arraybuffer'}, onComplete);

    if (!loadCache[path]) {
        loadCache[path] = new Promise(async (resolve) => {
            const svgaParser = new SVGA.Parser({
                // 是否取消使用 WebWorker，默认值 false
                isDisableWebWorker: CC_EDITOR,

                // 是否取消使用 ImageBitmap 垫片，默认值 false
                isDisableImageBitmapShim: true, // 傻逼来的，会把半透明的变成黑底
            });
            const videoItem = await svgaParser.load(path);

            resolve(videoItem);
        });
    }

    const videoItem = await loadCache[path];
    onComplete(null, videoItem);

});

export const ImgCache: { [key in string]: HTMLImageElement } = {}

export function createImageAsync(src) {
    return new Promise<HTMLImageElement>((resolve) => {
        if (ImgCache[src]) {
            resolve(ImgCache[src]);
        } else {
            const img = new Image();
            img.onload = () => {
                ImgCache[src] = img;
                resolve(img);
            }
            img.src = src;
        }
    });
}

export const SpCache: { [key in string]: SpriteFrame } = {}

export async function createSpriteFrameAsync(src) {
    if (SpCache[src]) {
        return SpCache[src];
    }

    const img = await createImageAsync(src);
    const texture = new Texture2D();
    texture.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE);
    texture.image = new ImageAsset(img);
    const sp = new SpriteFrame();
    sp.texture = texture;

    SpCache[src] = sp;

    return sp;
}

export function createImage(src) {
    if (ImgCache[src]) return ImgCache[src];
    const img = new Image();
    ImgCache[src] = img;    // 不在onload之后应该没事吧
    img.src = src;
    return img;
}
