import { GlobalLoader } from "../2d/loader";
import { ArrayBufferToBase64, decodeText } from "../2d/utils";
import { createTexturesByAtlas } from "./loadAtlas";
import { BaseTexture } from "../2d/texture";
import { ISkeletonData, Spine } from "./Spine";


/**
 * 加载spi文件，直接返回显示对象吧，数据不暴露了，spine有clone方法，用原数据生成，以后有需求单独加载数据再说
 * @param url 
 * @param onLoad 到底怎么返回，只返回数据吧，对象自己new，还是直接返回对象，其实数据没必要暴露，svga是因为解析不带任何显示对象，只能返回数据
 * @param onError 
 */
export function loadSpine(
    url: string,
    onLoad: (spineData: ISkeletonData) => void,
    onError?: (err: any) => void,
) {
    GlobalLoader.loadAB(async (s, res) => {
        if (!s) {
            onError && onError(res);
            return
        }
        try {
            var headerView = new DataView(res, 0, 12);
            var imgLen = headerView.getUint32(0, true),
                atlasLen = headerView.getUint32(4, true),
                jsonLen = headerView.getUint32(8, true)

            var base64String = `data:image/png;base64,${ArrayBufferToBase64(res.slice(12, imgLen + 12))}`;
            var atlas = decodeText(new Uint8Array(res, 12 + imgLen, atlasLen));
            var json = JSON.parse(decodeText(new Uint8Array(res, 12 + imgLen + atlasLen, jsonLen)));

            GlobalLoader.loadImage((s, image) => {
                //纹理加上
                json.textures = createTexturesByAtlas(BaseTexture.fromImage(image), atlas);
                //后续删除
                Object.defineProperty(json, 'spine', {
                    get: function () {
                        console.warn("loadSpine方法不再返回spine对象，请使用new Spine(spineData)生成实例");
                        return new Spine(json)
                    }
                })
                //后续删除
                Object.defineProperty(json, 'skeletonData', {
                    get: function () {
                        console.warn("loadSpine方法返回的是整个skeletonData了，不再是json.skeletonData");
                        console.warn("Spine构造函数直接传loadSpine加载成功的数据就行，不再分开传skeletonData和textures");
                        return json
                    }
                })
                //成功回调
                onLoad && onLoad(json);
            }, base64String)
        } catch (e) {
            onError && onError(e);
        }

    }, url)
}