import MSVGAClip from "../MComponents/MSVGAClip";
import Pool, { PoolGroup } from "../MComponents/Pool";

export default class SVGAMgr {
    private static _parser: any = null;
    public static get parser(): any {
        if (SVGAMgr._parser == null) {
            SVGAMgr._parser = new window["SVGA"].Parser();
        }
        return SVGAMgr._parser;
    }
    private static videoItemCache: { [key: string]: any } = {};

    private static poolGroup: PoolGroup<MSVGAClip> = new class extends PoolGroup<MSVGAClip>{
        protected createPool(name: string) {
            return new class extends Pool<MSVGAClip>{
                protected createElement() {
                    let videoItem = SVGAMgr.videoItemCache[name];
                    if (videoItem) {
                        let svga: SVGAMovieClip = new window["SVGA"].EgretMovieClip(videoItem);
                        svga.visible = false;
                        svga.gotoAndStop(1);
                        return new MSVGAClip(name, svga);
                    } else {
                        return null;
                    }
                }
            }();
        }
    }();

    /**加载videoItem */
    public static loadRes(name: string, url: string) {
        return new Promise<void>(resolve => {
            SVGAMgr.parser.load(window["svgaUrlPrefix"] + url, (videoItem: any) => {
                SVGAMgr.videoItemCache[name] = videoItem;
                resolve();
            });
        });
    }

    /**获取MSVGAClip实例 */
    public static create(name: string, parent: egret.DisplayObjectContainer): MSVGAClip {
        let clip = this.poolGroup.get(name);
        parent.addChild(clip.svga);
        return clip;
    }

    public static recycle(name: string, clip: MSVGAClip) {
        this.poolGroup.recycle(name, clip);
    }
}