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

export class Utils {
    /**
     * 加载SpriteFrame
     * @param url 资源地址
     * @param onSuccess 成功回调
     */
    public static LoadSpriteFrame(url: string, onSuccess: (spriteFrame: SpriteFrame) => void) {
        if (url.startsWith("data:image/")) {
            const img = new Image();
            img.src = url;
            const tex = new Texture2D();
            img.onload = () => {
                tex.reset({
                    width: img.width,
                    height: img.height,
                });
                tex.uploadData(img, 0, 0);
                const sp = new SpriteFrame();
                sp.texture = tex;
                onSuccess(sp);
            };
        } else if (url.startsWith("http")) {
            assetManager.loadRemote<ImageAsset>(url, {ext: ".jpg"}, (err, imageAsset) => {
                if (err) return;
                const spriteFrame = new SpriteFrame();
                const texture = new Texture2D();
                texture.image = imageAsset;
                spriteFrame.texture = texture;
                onSuccess(spriteFrame);
            });
        } else {
            resources.load(url + "/spriteFrame", SpriteFrame, (err, spriteFrame) => {
                if (err) return;
                onSuccess(spriteFrame);
            });
        }
    }
}


