
/**
 * 直接通过替换source替换图片的动画帧
 * 暂时这些动画帧只播放一次，所以简化
 * 默认按时间间隔播放
 * 图片都以素材为中心为原点
 */
export class ImageAni extends eui.Image {
    sourceAll: string[];
    currentFrame: number;
    totalFrames: number;
    isPlay: boolean;

    startTime: number
    /**
     * 所有时间，帧数按每秒30
     */
    allTime: number
    /**
     * 播放完的回调
     */
    callback: Function;
    /**
     * 
     * @param sourceAll 所有的资源数组
     */
    constructor(sourceAll: string[]) {
        super()
        this.sourceAll = sourceAll;
        this.texture = RES.getRes(sourceAll[0])
        // this.source = sourceAll[0];
        // this.x = -this.texture.textureWidth / 2;
        // this.y = -this.texture.textureHeight / 2;
        this.currentFrame = 0;
        this.totalFrames = sourceAll.length;
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)

        this.allTime = this.sourceAll.length / 30 * 1000;
    }
    //需要做锁步
    private count = 0;
    onEnterFrame() {
        if (!this.isPlay) {
            // this.count = 0
            return
        }
        // this.count++;
        // if (this.count % 2 == 0) {
        //     this.currentFrame++;
        //     if (this.currentFrame == this.totalFrames/*-1*/) {
        //         this.currentFrame = 0;
        //         this.isPlay = false
        //         this.callback && this.callback();
        //     }
        //     this.texture = RES.getRes(this.sourceAll[this.currentFrame])
        //     this.x = -this.texture.textureWidth / 2;
        //     this.y = -this.texture.textureHeight / 2;
        // }
        var dataNow = Date.now();
        var deltaTime = dataNow - this.startTime;
        var scale = deltaTime / this.allTime;
        if (scale >= 1) {
            this.isPlay = false
            this.callback && this.callback();
            //重复播放
            this.play();
        } else {
            this.currentFrame = (scale * this.sourceAll.length) >> 0;
            this.texture = RES.getRes(this.sourceAll[this.currentFrame])
            // this.x = -this.texture.textureWidth / 2;
            // this.y = -this.texture.textureHeight / 2;
        }
    }
    /**
     * 从0开始播
     * 回调是播放完后做回收用的
     */
    play(callback?) {
        this.startTime = Date.now();
        this.isPlay = true;
        this.currentFrame = 0;
        this.texture = RES.getRes(this.sourceAll[this.currentFrame])
        // this.x = -this.texture.textureWidth / 2;
        // this.y = -this.texture.textureHeight / 2;
        this.callback = callback;
    }

    /**
     * 啥特效就是啥
     */
    reset() {
        this.isPlay = false;
        this.currentFrame = 0;
        this.texture = RES.getRes(this.sourceAll[0])
        this.x = -this.texture.textureWidth / 2;
        this.y = -this.texture.textureHeight / 2;
    }
}