import BaseTexture from "./BaseTexture";
import { Rectangle } from "../math";
import Texture from "./Texture";

interface dataTm {
    x: number,  //x,y,w,h为图集上的切图位置数据
    y: number,
    w: number,
    h: number,
    ox: number,  //ox,oy为偏移数据，trim裁剪的数据，在orig上的偏移{x:0,y:0,width:200,height:200}
    oy: number,
    sw: number, //sw,sh为原始宽高
    sh: number,
    ro: boolean, //是否旋转
}
//简化后的格式
var expData = {
    "actOverTitle.png": { "x": 1, "y": 1, "w": 474, "h": 172, "ox": 0, "oy": 0, "sw": 474, "sh": 172, "ro": false },
    "hasActOverLotBtn.png": { "x": 1, "y": 175, "w": 259, "h": 85, "ox": 0, "oy": 0, "sw": 259, "sh": 85, "ro": false }
}

/**
 * 
 * @param {BaseTexture} baseTexture 
 * @param {dataTm} altaData 
 * @return 返回贴图集。不常用
 */
export function createTextureSheet(baseTexture: BaseTexture, altaData): { [key: string]: Texture } {
    var frames = altaData;
    var frameKeys = Object.keys(frames);
    let frameIndex = 0;
    //要返回的贴图集合
    var textures: { [key: string]: Texture } = {};

    while (frameIndex < frameKeys.length) {
        //名字
        const i = frameKeys[frameIndex];
        //数据
        const data: dataTm = frames[i];
        //切图上的数据
        let frame: Rectangle = null;
        //裁切的数据
        let trim: Rectangle = null;
        //贴图原始尺寸
        const orig = new Rectangle(
            0,
            0,
            Math.floor(data.sw),
            Math.floor(data.sh)
        );

        //如果旋转过
        if (data.ro) {
            frame = new Rectangle(
                Math.floor(data.x),
                Math.floor(data.y),
                Math.floor(data.h),
                Math.floor(data.w)
            );
        } else {
            frame = new Rectangle(
                Math.floor(data.x),
                Math.floor(data.y),
                Math.floor(data.w),
                Math.floor(data.h)
            );
        }
        //如果是被截掉过透明边界的 ,,加上如果和原始尺寸不一致也是裁切
        if (data.ox || data.oy || data.w != data.sw || data.h != data.sh) {
            //其实就是在orig上切图，偏移
            trim = new Rectangle(
                Math.floor(data.ox),
                Math.floor(data.oy),
                Math.floor(data.w),
                Math.floor(data.h)
            );
        }

        var texture = new Texture(
            baseTexture,
            frame,
            orig,
            trim,
            data.ro ? 2 : 0,
            // data.anchor
        );
        //缓存下
        Texture.addToCache(texture, i);
        textures[i] = texture;
        frameIndex++;
    }

    return textures;
}