//订阅者回调签名
typedef void EventCallback(arg);

class MessageMgr {

  static const  String REFRESH_PUSH_PERMISSION ='refresh_push_permission';
  static const  String RECEIVE_THIRD_SHARE ='receive_third_share';

  static const  String TRANSLATE_HK_REFRESH_ORDER ='translate_hk_refresh_order';
  static const  String TRANSLATE_HK_RECEIVE_ORDER ='translate_hk_receive_order';
  static const  String TRANSLATE_HK_CANCEL_ORDER ='translate_hk_cancel_order';
  static const  String TRANSLATE_HK_START_CHAT ='translate_hk_start_chat';
  static const  String TRANSLATE_HK_END_CHAT ='translate_hk_end_chat';


  //私有构造函数
  MessageMgr._internal();

  //保存单例
  static MessageMgr _singleton = new MessageMgr._internal();

  //工厂构造函数
  factory MessageMgr() => _singleton;

  //保存事件订阅者队列，key:事件名(id)，value: 对应事件的订阅者队列
  var _emap = new Map<Object, List<EventCallback>>();

  //添加订阅者
  void on(eventName, EventCallback f) {
    if (eventName == null || f == null) return;
    _emap[eventName] ??= new List<EventCallback>();
    _emap[eventName].add(f);
  }

  //移除订阅者
  void off(eventName, [EventCallback f]) {
    var list = _emap[eventName];
    if (eventName == null || list == null) return;
    if (f == null) {
      _emap[eventName] = null;
    } else {
      list.remove(f);
    }
  }

  //触发事件，事件触发后该事件所有订阅者会被调用
  void emit(eventName, [arg]) {
    var list = _emap[eventName];
    if (list == null) return;
    int len = list.length - 1;
    //反向遍历，防止在订阅者在回调中移除自身带来的下标错位
    for (var i = len; i > -1; --i) {
      list[i](arg);
    }
  }
}
