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

/**
 * 包括动画数据和图集数据的原始数据，可复用
 */
export interface SpineData {
    /**
     * 骨骼动画数据
     */
    skeletonData: ISkeletonData,
    /**
     * 纹理数据
     */
    textures: { [key: string]: Texture },
    /**
     * 返回的一个显示对象实例
     */
    spine: Spine
}
/**
 * 加载spi文件，直接返回显示对象吧，数据不暴露了，spine有clone方法，用原数据生成，以后有需求单独加载数据再说
 * @param url 
 * @param onLoad 到底怎么返回，只返回数据吧，对象自己new，还是直接返回对象，其实数据没必要暴露，svga是因为解析不带任何显示对象，只能返回数据
 * @param onError 
 */
export function loadSpine(
    url: string,
    onLoad: (spineData: SpineData) => 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) => {
                var textures = createTexturesByAtlas(BaseTexture.fromImage(image), atlas);
                onLoad && onLoad(
                    {
                        skeletonData: json,
                        textures,
                        spine: new Spine(json, textures)
                    }
                )
            }, base64String)
        } catch (e) {
            onError && onError(e);
        }

    }, url)
}