const DefaultDtFactor = 60 / 1000;

export default class MTimer {
    private static onFrameList: ((dt: number, self: Function) => void)[] = [];
    private static timerList: ((self: Function) => void)[] = [];

    public static deltaTime: number = 0;
    public static get dtFactor() {
        return MTimer.deltaTime * DefaultDtFactor;
    }

    public static init() {
        egret.MainContext.instance.stage.addEventListener(egret.Event.ENTER_FRAME, () => {
            for (let i = 0; i < MTimer.onFrameList.length; i++) {
                MTimer.onFrameList[i](MTimer.deltaTime, MTimer.onFrameList[i]);
            }

            for (let i = 0; i < MTimer.timerList.length; i++) {
                MTimer.timerList[i](MTimer.timerList[i]);
            }
        }, MTimer);
    }

    private static removeOnFrame(callback: Function) {
        MTimer.onFrameList = MTimer.onFrameList.filter(e => e != callback);
    }

    public static set(frame: number, onTimeOut: () => void) {
        let count = 0;
        MTimer.timerList.push((self: Function) => {
            count += MTimer.dtFactor;
            if (count >= frame) {
                onTimeOut();
                MTimer.timerList = MTimer.timerList.filter(e => e != self);
            }
        });
    }

    public static onFrame(callback: (deltaTime: number, remove?: () => void) => void, frameCount?: number) {
        if (typeof frameCount != "undefined") {
            let count = 0;
            MTimer.onFrameList.push((deltaTime: number, self: Function) => {
                callback(deltaTime);
                count += MTimer.dtFactor;
                if (count >= frameCount) {
                    MTimer.removeOnFrame(self);
                }
            });
        } else {
            MTimer.onFrameList.push((deltaTime: number, self: Function) => {
                callback(deltaTime, () => {
                    MTimer.removeOnFrame(self);
                });
            });
        }
    }
}


class MTimerObject {
    private timer: egret.Timer = null;

    constructor(time: number, onTimeOut: () => void, repeat?: number, onRepeated?: () => void) {
        //创建一个计时器对象
        let timer: egret.Timer = new egret.Timer(time, repeat || 1);
        //注册事件侦听器
        timer.addEventListener(egret.TimerEvent.TIMER, onTimeOut, this);
        timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, onRepeated || (() => { }), this);
        //开始计时
        timer.start();
        this.timer = timer;
    }

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