import { _decorator, CCString, Component, Node, Sprite, SpriteFrame, Texture2D, UITransform, v2 } from 'cc';
import { MyAnimation } from './MyAnimation';
import { GameScript } from '../GameScript/GameScript';
import { ImagePack } from '../ImagePack/ImagePack';
import { ScriptAni } from '../GlobalInterface/GlobalInterface';
const { ccclass, property, requireComponent } = _decorator;

@ccclass('ScriptMyAnimation')
@requireComponent(Sprite)//依赖组件 精灵
export class ScriptMyAnimation extends MyAnimation {


    @property({ type: CCString, displayName: 'Ani路径', tooltip: "Ani在PVF中的路径" })
    AnimationPath: string = "";

    //是否有替换符
    Replace: Array<string>;

    //读取Img
    InitImg() {
        //遍历img路径数组
        this.AniObject.Img_List.forEach((Path, index) => {
            ImagePack.getInstance().ReadNpkTable("sprite/" + Path.toLocaleLowerCase(), (ImgObj) => {
                this.LoadSuccessImgCount++;
                //记录路径对应的Img对象
                this.ImgTable.set(Path, ImgObj);
                //如果已加载数量等于总数量 说明Img初始化完成
                if (this.LoadSuccessImgCount == this.AniObject.Img_List.length) {
                    //都加载完成以后 把精灵帧初始化出来
                    this.FrameArr.forEach((FrameObj, Index) => {
                        const Png = this.ImgTable.get(FrameObj.Img_Path).Png_List[FrameObj.Img_Index];

                        let spriteFrame = new SpriteFrame();
                        let tex = new Texture2D();
                        tex.reset({
                            width: Png.Width,
                            height: Png.Height,
                            format: Texture2D.PixelFormat.RGBA8888,
                            mipmapLevel: 0,
                        });
                        tex.uploadData(Png.PNGdata);
                        // 更新 0 级 Mipmap。
                        tex.updateImage();
                        spriteFrame.texture = tex;
                        spriteFrame.offset = v2(Png.Xpos, -Png.Ypos);

                        this.FrameArr[Index].Frame = spriteFrame;
                    });
                    this.InitState = true;
                    //开始播放
                    this.PlayState = 1;
                }
            });
        });
    }

    //通过路径初始化Ani对象
    InitAnimotionObject() {
        this.AniObject = GameScript.getInstance().GetDataByPath(this.AnimationPath);
    }

    Init() {
        if (!this.AniObject) this.InitAnimotionObject();

        //如果有替换符则替换
        if (this.Replace) {
            this.AniObject.Frame.forEach((FrameObj, Index) => {
                this.AniObject.Frame[Index].Img_Path = FrameObj.Img_Path.replace(this.Replace[0], this.Replace[1]);
            });
        }

        this.FrameArr = this.AniObject.Frame;

        this.InitImg();
    }


    start() {
        super.start();
    }


}


