import {
    _decorator, Color, Component, math, Node, resources, Sprite, SpriteFrame, Texture2D, UITransform, v2, v3, Vec2, Vec3,
} from "cc";
import { GameState } from "../GlobalGameState/GameState";
import { ImagePack } from "../ImagePack/ImagePack";
import { Ani_Frame, Img, ScriptAni } from "../GlobalInterface/GlobalInterface";
import { GameScript } from "../GameScript/GameScript";
const { ccclass, property, requireComponent } = _decorator;


@ccclass("MyAnimation")
@requireComponent(Sprite)
export class MyAnimation extends Component {
    //Ani加载精灵帧初始化状态
    InitState: boolean = false;

    SpriteObj: Sprite = null;

    //Ani帧数
    AnimationFrameCount: number = 1;

    //默认img路径
    DefaultImgPath: string = "";

    //img路径的数组
    ImgPath: string[] = Array<string>();
    ImgIndex: number[] = Array<number>();
    //img帧的数组
    FrameArr: Array<Ani_Frame> = [];

    //实际用到的Img路径数组 可能用于以后的释放NPK
    RealUseImgPath: string[] = Array<string>();

    //播放计时器时间
    PlayTimer: number = 0;

    //每帧延迟时间
    FrameDelay: number[] = Array<number>();

    //当前帧
    NowFrame: number = 0;


    //Ani播放状态 0未播放 1播放中 2暂停中 3播放完成
    PlayState = 0;

    //Ani对象
    AniObject: ScriptAni;


    //初始化路径
    InitPath() {
        //首先push默认路径
        this.RealUseImgPath.push(this.DefaultImgPath);

        //遍历img路径数组
        this.ImgPath.forEach((Path, index) => {
            //如果没填写说明为空
            if (Path == "") {
                Path = this.DefaultImgPath;
            } else {
                if (!this.RealUseImgPath.includes(Path)) {
                    this.RealUseImgPath.push(Path);
                }
            }
            this.FrameArr.push({
                Img_Path: Path,
                Img_Index: this.ImgIndex[index],
                Delay: this.FrameDelay[index],
                Frame: null,
            });
        });
    }

    LoadSuccessImgCount: number = 0;
    ImgTable: Map<string, Img> = new Map<string, Img>();
    //读取Img
    InitImg() {
        //遍历img路径数组
        this.RealUseImgPath.forEach((Path, index) => {
            ImagePack.getInstance().ReadNpkTable(Path, (ImgObj) => {
                this.LoadSuccessImgCount++;
                //记录路径对应的Img对象
                this.ImgTable.set(Path, ImgObj);
                //如果已加载数量等于总数量 说明Img初始化完成
                if (this.LoadSuccessImgCount == this.RealUseImgPath.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, 0);
                        // 更新 0 级 Mipmap。
                        tex.updateImage();
                        spriteFrame.texture = tex;
                        spriteFrame.offset = v2(Png.Xpos, -Png.Ypos);

                        this.FrameArr[Index].Frame = spriteFrame;
                    });
                    this.InitState = true;
                }
            });
        });
    }

    Init() {
        this.InitPath();

        this.InitImg();
    }

    start() {
        //判断是否有精灵 如果没有 就给他搞一个
        if (this.node.getComponent(Sprite))
            this.SpriteObj = this.node.getComponent(Sprite);
        else
            this.SpriteObj = this.node.addComponent(Sprite);


        //初始化构造内容
        this.Init();

        //设置节点锚点为左上角
        this.node.getComponent(UITransform).anchorPoint = v2(0, 1);
        //设置类型
        this.SpriteObj.sizeMode = Sprite.SizeMode.RAW;
        //设置
        this.SpriteObj.trim = false;
    }

    update(deltaTime: number) {

        //如果游戏世界处于暂停的模式下 不再继续播放
        if (GameState.getInstance().IsPauseState()) return;
        //如果初始化未完成，不播放
        if (!this.InitState) return;
        //如果不在播放中
        if (this.PlayState != 1) return;

        let FrameObj = this.FrameArr[this.NowFrame];
        if (FrameObj) {
            //当前帧播放时间大于本帧延迟时间时
            if (this.PlayTimer > FrameObj.Delay) {

                //需要初始化还原的东西
                //缩放
                this.node.setScale(1, 1);
                //染色
                this.SpriteObj.color = new Color(255, 255, 255, 255);




                //帧数加1
                this.NowFrame++;
                //Ani播放完了
                if (this.NowFrame >= this.FrameArr.length) {
                    if (this.AniObject && this.AniObject.Flag && this.AniObject.Flag.get("LOOP"))
                        this.NowFrame = 0;
                    else this.PlayState = 3;
                }

                //设置精灵对象更换图片
                this.SpriteObj.spriteFrame = FrameObj.Frame;

                //设置坐标
                if (FrameObj.Pos) this.node.setPosition(FrameObj.Pos);

                if (FrameObj.Flag) {
                    if (FrameObj.Flag.get("INTERPOLATION")) {
                        
                    } else {
                        FrameObj.Flag.forEach((Value, Key) => {
                            if (Key == "RGBA") {
                                this.SpriteObj.color = new Color(Value[0], Value[1], Value[2], Value[3]);
                            }
                            else if (Key == "IMAGE_RATE") {
                                this.node.setScale(parseFloat(Value.x), parseFloat(Value.y));
                            }
                        });
                    }
                }


                //重置计时器
                this.PlayTimer = 0;
            }
        }
        this.PlayTimer += deltaTime * 1000;
    }
}
