export default class SheetAnimation extends egret.Bitmap {
    private _counter: number;
    private _sheet: egret.SpriteSheet;
    private _fps = 24;
    private _fpscounter = 1;
    totalFrames: number;
    onEnterFrame() {
        if (this._fpscounter == 1) {
            let key = '0' + this._counter;
            if (this._counter >= 10)
                key = this._counter + '';

            const picData = this._sheet.getTexture(key);
            this.$setBitmapData(picData);
            this.dispatchEvent(new egret.Event('frameUpdate', false, false, this._counter));
            this._counter++;
            if (this._counter > this.totalFrames)
                this._counter = 1;
        }

        this._fpscounter++;
        if (this._fpscounter > Math.ceil(60 / this._fps))
            this._fpscounter = 1;
    }

    set sheet(val: egret.SpriteSheet) {
        this._sheet = val;
        this.stopAtFirstFrame();
        this.totalFrames = this.getTotalFrames() - 1;
    }

    get sheet(){return this._sheet}

    private getTotalFrames() {
        let counter = 0;
        for (const key in this._sheet._textureMap) {
            counter++;
        }
        return counter;
    }

    stopAtFirstFrame() {
        const picData = this._sheet.getTexture('01');
        this.$setBitmapData(picData);
        this.stop();
    }

    stopAtIdleFrame() {
        const picData = this._sheet.getTexture('00');
        this.$setBitmapData(picData);
        this.stop();
    }

    set fps(val: number) {
        this._fps = val;
    }

    play() {
        this._fpscounter = 1;
        this._counter = 1;
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

    private stop() {
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

    destroy() {
        this.stop();
        this._sheet = null;
    }
}