import Pool, { PoolGroup } from "../components/Pool";
import SVGAClip from "../components/SVGAClip";
import GameMgr from "./GameMgr";
import GameStage from "../Game/GameStage";

export default class ParticleMgr {
    public gameStage: GameStage = null;
    constructor(gameStage: GameStage) {
        this.gameStage = gameStage;
    }

    /* public loadSvga(url: string) {
        return new Promise<SVGAClip>(resolve => {
            SVGAClip.parser.load(url, (videoItem: any) => {
                let svga: SVGAClip = new SVGAClip(new window["SVGA"].EgretMovieClip(videoItem), this.gameStage);
                // svga.init();
                resolve(svga);
            });
        });
    } */
    private createMovieClip(name: string) {
        let factory = this.movieClipFactoryCache[name];
        if (!factory) {
            var data = RES.getRes(name + "_json");
            var txtr: egret.Texture = RES.getRes(name + "_png");
            if (!data) console.error("can not find the json");
            if (!txtr) console.error("can not find the png");
            this.movieClipFactoryCache[name] = new egret.MovieClipDataFactory(data, txtr);
            factory = this.movieClipFactoryCache[name];
        }

        let movieClip = new egret.MovieClip(factory.generateMovieClipData(name));
        if (movieClip.$movieClipData.frames.length <= 0) console.error("frame is null");

        if (name == "ant_die") {
            this.gameStage.shadowLayer.addChild(movieClip);
        } else {
            this.gameStage.addChild(movieClip);
        }
        return movieClip;
    }

    private movieClipFactoryCache: {
        [key: string]: egret.MovieClipDataFactory
    } = {};

    //定义内存池组，并创建内存池组的实例类的实例
    private poolGroup: PoolGroup<egret.MovieClip> = new class extends PoolGroup<egret.MovieClip>{ //实现内存池组抽象类
        //实现创建内存池方法
        protected createPool(key: string) {
            //返回一个内存池实例类的实例
            return new class extends Pool<egret.MovieClip>{ //实现内存池抽象类
                //实现创建内存池元素的方法
                protected createElement() {
                    //返回加载后的动画实例
                    return GameMgr.instance.particleMgr.createMovieClip(key);
                }

                protected onElementInit(e: egret.MovieClip) {
                    e.visible = true;
                }

                onElementRecycle(e: egret.MovieClip) {

                    e.visible = false;
                }
            }();
        }
    }();

    public get(name: string) {
        let movieClip = this.poolGroup.get(name);
        movieClip.once(egret.Event.COMPLETE, () => {
            this.poolGroup.recycle(name, movieClip);
        }, this);
        return movieClip;
    }
}