import 'event_center.dart';

/// 设备事件处理器（绑定指定Status）
abstract class DeviceEventStatusHandler {
  /// 绑定状态
  final int status;

  DeviceEventStatusHandler(this.status);

  /// 处理事件
  void handle(Map<String, dynamic>? data);
}

/// 全局设备事件处理器
abstract class GlobalDeviceEventHandler {
  static final _statusHandlerMap = <int, DeviceEventStatusHandler>{};
  static final _listener = DeviceEventListener(
    accpetStatusList: null,
    callback: _onEventCallback,
  );

  /// 安装加载
  static void setup({List<DeviceEventStatusHandler>? statusHandlers}) {
    if (statusHandlers != null) {
      _loadStatusHandlers(statusHandlers);
    }
    DeviceEventCenter.instance.addListener(_listener);
    // TODO: log
  }

  static void _loadStatusHandlers(List<DeviceEventStatusHandler> handlers) {
    for (final handler in handlers) {
      _statusHandlerMap[handler.status] = handler;
    }
  }

  static void _onEventCallback(int status, Map<String, dynamic>? data) {
    if (_statusHandlerMap.containsKey(status)) {
      final handler = _statusHandlerMap[status]!;
      handler.handle(data);
      // TODO: log status handled!
    }
  }
}
