/**
 * 事件模块
 * onfire.js
 * 
 */
interface Listener {
  cb: Function;
  once: boolean;
  target: object;
}

interface EventsType {
  [eventName: string]: Listener[];
}
class EventMgr {
  // 所有事件的监听器
  es: EventsType = {};

  on(eventName: string, cb: Function, target: object) {
    if (!this.es[eventName]) {
      this.es[eventName] = [];
    }

    this.es[eventName].push({
      cb,
      once: false,
      target,
    });
  }

  once(eventName: string, cb: Function, target: object) {
    if (!this.es[eventName]) {
      this.es[eventName] = [];
    }

    this.es[eventName].push({
      cb,
      once: true,
      target,
    });
  }

  emit(eventName: string, params?: any) {
    const listeners = this.es[eventName] || [];

    let l = listeners.length;

    for (let i = 0; i < l; i++) {
      const { cb, once, target } = listeners[i];
      let args = [eventName, params];
      cb.apply(target, args);

      if (once) {
        listeners.splice(i, 1);
        i--;
        l--;
      }
    }
  }

  off(eventName?: string, cb?: Function, target?: object) {
    // clean all
    if (eventName === undefined) {
      this.es = {};
    } else {
      if (cb === undefined) {
        // clean the eventName's listeners
        delete this.es[eventName];
      } else if (cb === null) {
        if (!target) {
          return;
        }
        const listeners = this.es[eventName] || [];
        // clean the event and listener
        let l = listeners.length;
        for (let i = 0; i < l; i++) {
          if (listeners[i].target === target) {
            listeners.splice(i, 1);
            i--;
            l--;
          }
        }
      } else {
        const listeners = this.es[eventName] || [];
        // clean the event and listener
        let l = listeners.length;
        for (let i = 0; i < l; i++) {
          if (listeners[i].cb === cb && listeners[i].target === target) {
            listeners.splice(i, 1);
            i--;
            l--;
          }
        }
      }
    }
  }
}

export default new EventMgr();