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

/*
  Subscription? subscribe;

  void registerEventBus() {
    subscribe = bus.on(AppConstant.eventProfileRefresh, (arg) {
      Log.d("Home - 接收消息");
    });
  }

  void unregisterEventBus() {
    bus.off(AppConstant.eventProfileRefresh, subscribe);
    Log.d("Home - 解注册这个Key的消息");
  }

  //发送事件
    bus.emit(AppConstant.eventProfileRefresh, true);
 */

//定义一个top-level（全局）变量，页面引入该文件后可以直接使用bus
var bus = EventBus();

class EventBus {

  EventBus._internal();

  //保存单例
  static final EventBus _singleton = EventBus._internal();

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

  final _subscriptions = <String, List<Subscription>>{};

  /// 添加订阅者，返回一个 Subscription 对象，用于取消订阅
  Subscription on(String eventName, EventCallback callback) {
    final sub = Subscription(eventName: eventName, callback: callback);
    _subscriptions.putIfAbsent(eventName, () => []).add(sub);
    return sub;
  }

  /// 取消订阅（如果指定了 callback，则只取消对应的订阅者；否则取消所有订阅者）
  void off(String eventName, [Subscription? subscription]) {
    if (_subscriptions.containsKey(eventName)) {
      if (subscription == null) {
        _subscriptions[eventName]!.clear();
      } else {
        _subscriptions[eventName]!.removeWhere((sub) => sub.callback == subscription.callback);
      }
    }
  }

  /// 取消所有订阅
  void offAll() {
    _subscriptions.clear();
  }

  /// 触发事件，通知所有订阅者
  void emit(String eventName, [arg]) {
    for (final sub in _subscriptions[eventName] ?? []) {
      sub.callback(arg);
    }
  }
}

/// Subscription 对象，用于取消订阅
class Subscription {

  final String eventName;
  final EventCallback callback;

  Subscription({required this.eventName, required this.callback});
}
