import Singleton from "../plugin/Singleton";
import LogMgr from "./LogMgr";

export default class EventManager extends Singleton {
    private static events: { [key: string]: { target: any, callBack: Function }[] } = {};

    static init() {
        this.events = {};
        LogMgr.log(`事件管理器初始化成功`);
    }
    /**注册事件
     * @param eventName 事件名
     * @param callBack 回调函数
     * @param target 回调函数的this
     */
    static on(eventName: string, callBack: Function, target: any) {
        if (!this.events[eventName]) {
            this.events[eventName] = [];
        }
        this.events[eventName].push({ target: target, callBack: callBack });
        LogMgr.log(`注册事件${eventName},::${this.events[eventName]}`);
    }
    /**发射事件
     * @param eventName 事件名
     * @param args 参数数组
     */
    static emit(eventName: string, ...args: any[]) {
        let eventCB = this.events[eventName];
        if (eventCB) {
            eventCB.forEach((ec) => {
                ec.callBack.call(ec.target, ...args);
            });
        }
    }
    /**取消监听事件
     * @param eventName 事件名
     */
    static off(eventName: string, callBack: Function) {
        let eventCB = this.events[eventName];
        if (eventCB) {
            this.events[eventName] = eventCB.filter(ec => ec.callBack !== callBack);
        }
    }
    /**取消所有事件     */
    static offAll() {
        this.events = {};
    }
}