export default class MovieClip extends engine.Image {
    textures: engine.Texture[];
    frames: string[];
    keys: string[];
    autoplay: boolean;
    loop: boolean;
    anchorXtmp: number;
    anchorYtmp: number;
    currentFrame: number;
    frameInterval: number;
    counter: number;
    scale: number;
    _callBack:any;

    constructor({ spritesheet, frames, scale, position, keys = null, autoplay = true, loop = true, anchor, frameInterval = 1 ,callBack=null}) {
        super();
        this.frames = frames;
        this.frameInterval = frameInterval;
        this.keys = keys;
        this.autoplay = autoplay;
        this.loop = loop;
        this.anchorXtmp = anchor;
        this.anchorYtmp = anchor;
        this._callBack = callBack;
        if (Array.isArray(anchor)) {
            this.anchorXtmp = anchor[0];
            this.anchorYtmp = anchor[1];
        }
        this.x = position[0];
        this.y = position[1];
        this.spritesheet = spritesheet;
        if (this.autoplay) {
            this.play();
        }
        this.scaleX = this.scaleY = scale;
    }

    pause() {
        //egret.stopTick(this.onTick, this);
        this.removeEventListener(engine.Event.ENTER_FRAME, this.onTick, this)
    }

    resume() {
        //egret.startTick(this.onTick, this);
        this.addEventListener(engine.Event.ENTER_FRAME, this.onTick, this)
    }

    play(start = 0) {
        this.goto(start);
        this.currentFrame = 0;
        this.counter = 0;
        //egret.startTick(this.onTick, this);
        this.addEventListener(engine.Event.ENTER_FRAME, this.onTick, this)
    }

    goto(frame: number) {
        this.texture = this.textures[frame];
    }

    onTick() {
        this.counter++;
        if (this.counter == this.frameInterval) {
            this.counter = 0;
            this.currentFrame++;
            this.goto(this.currentFrame);
            if (this.currentFrame == this.frames.length - 1) {
                if (this.loop) {
                    this.currentFrame = 0;
                } else {
                   
                    this.stop();
                    //true
                    if(this._callBack){
                        this._callBack();
                        this._callBack = null
                    }
                    //this.dispatchEvent('boomOver',null,true)
                }
            }
        }
        return false;
    }

    stop() {
        this.currentFrame = 0;
        this.removeEventListener(engine.Event.ENTER_FRAME, this.onTick, this)
        //egret.stopTick(this.onTick, this);
       
    }

    set spritesheet(value) {
        //this.frames.map(frame => value.getTexture(frame));
        this.textures = this.frames.map(frame => value[frame]);

        this.anchorTexture.set(this.anchorXtmp,this.anchorYtmp)
    }

    private get textureItemWidth() { return this.textures[0].width }
    private get textureItemHeight() { return this.textures[0].height }
}