import Pool, { PoolGroup, PoolElement } from "../Components/Pool";

export default class MovieClipMgr {
    private static _instance: MovieClipMgr = null;
    public static get instance(): MovieClipMgr {
        if (!this._instance) {
            this._instance = new MovieClipMgr();
        }

        return this._instance;
    }

    private movieClipData: { [name: string]: egret.MovieClipData } = {};

    private pool = new class extends PoolGroup<PoolMovieClip>{
        createPool(key: string) {
            return new class extends Pool<PoolMovieClip>{
                createElement() {
                    return MovieClipMgr.instance.create(key);
                }
            }();
        }
    }();

    public load(name: string): boolean {
        if (typeof this.movieClipData[name] == "undefined") {
            const data = RES.getRes(name + "_json");
            const txtr = RES.getRes(name + "_png");
            if (!data || !txtr) {
                console.error("can not load clip res:" + name);
                return false;
            }
            this.movieClipData[name] = new egret.MovieClipDataFactory(data, txtr).generateMovieClipData(name);
            return true;
        } else
            return true;
    }

    public create(name: string) {
        if (typeof this.movieClipData[name] == "undefined") {
            if (!this.load(name)) {
                return null;
            }
        }
        return new PoolMovieClip(this.movieClipData[name]);
    }

    public get(name: string): PoolMovieClip {
        return this.pool.get(name);
    }

    public recycle(name: string, clip: PoolMovieClip) {
        this.pool.recycle(name, clip);
        clip.destroy();
    }
}

class PoolMovieClip extends egret.MovieClip implements PoolElement {
    onElementInit() { }
    onElementRecycle() { }

    playOnComplete(): Promise<void> {
        this.gotoAndPlay(0, 1);
        return new Promise<void>(resolve => {
            this.once(egret.Event.COMPLETE, resolve, this);
        });
    }

    autoRecyclePlay(name: string) {
        this.playOnComplete().then(() => {
            MovieClipMgr.instance.recycle(name, this);
        });
    }
}