const DefaultDtFactor = 60 / 1000;

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

    public static deltaTime: number = 0;

    public static get dtFactor() {
        return SpTimer.deltaTime * DefaultDtFactor;
    }

    public static init() {
        egret.MainContext.instance.stage.addEventListener(egret.Event.ENTER_FRAME, SpTimer.onUpdate, SpTimer);
        // egret.startTick(SpTimer.onUpdate, SpTimer);
    }

    private static onUpdate() {
        for (let i = 0; i < SpTimer.onFrameList.length; i++) {
            SpTimer.onFrameList[i](SpTimer.deltaTime, SpTimer.onFrameList[i]);
        }

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

        return false;
    }

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

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

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