import { _decorator, CCInteger, 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 { ScriptAls, 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 = "";

    // @property({ type: CCInteger, displayName: '是否显示', tooltip: "1为显示 0为不显示" })
    // PlayState = 0;

    //是否有替换符
    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;
                }
            });
        });
    }

    Decompile_als(str: string) {
        const strbuf = str.split("\n");
        let Flag = 0;
        let AniobjArr: Array<string> = new Array<string>;
        let AniaddArr: Array<string[]> = new Array<string[]>;
        strbuf.forEach((lstr, line) => {
            if (Flag == 0) {
                if (lstr.indexOf("[use animation]") != -1) {
                    Flag = 1;
                } else if (lstr.indexOf("[none effect add]") != -1 || lstr.indexOf("[add]") != -1) {
                    Flag = 5;
                }
            } else if (Flag == 1) {
                AniobjArr.push(lstr);
                Flag = 2;
            } else if (Flag == 2) {
                AniobjArr.push(lstr);
                Flag = 0;
            } else if (Flag == 5) {
                let buf = lstr.split("\t");
                AniaddArr.push(buf);
                Flag = 0;
            }
        });

        let AniArr: Array<ScriptAls> = new Array<ScriptAls>;

        for (let index = 0; index < AniobjArr.length; index += 2) {
            let ScriptAlsBuf: ScriptAls = {};
            ScriptAlsBuf.Path = AniobjArr[index];
            ScriptAlsBuf.Name = AniobjArr[index + 1];
            AniArr.push(ScriptAlsBuf);
        }
        // console.log(AniobjArr);
        // console.log(AniaddArr);
        return AniArr;
    }

    //判断是否有Als
    CheckAnimotionAls() {
        let Ret = GameScript.getInstance().GetDataByPath(this.AnimationPath + ".als");
        if (Ret) {
            let Als = this.Decompile_als(Ret);
            Als.forEach(aniobj => {
                let NodeBuf = new Node();
                // let SpriteBuf = NodeBuf.addComponent(Sprite);
                let Ani = NodeBuf.addComponent(ScriptMyAnimation);

                Ani.AnimationPath = this.AnimationPath.substring(0, this.AnimationPath.lastIndexOf("/") + 1) + aniobj.Path.match(/`(.*?)`/)[1].toLowerCase();
                // Ani.PlayState = this.PlayState;
                // console.log(Ani.AnimationPath);
                this.node.parent.addChild(NodeBuf);
            });
        }
    }

    //通过路径初始化Ani对象
    InitAnimotionObject() {
        this.CheckAnimotionAls();
        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();
    }


}


