import 'package:vnote_device_plugin/consts/status.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vnote_device_plugin/devices/base.dart';
import 'package:vnote_device_plugin/events/event_type.dart';
import 'package:vnote_device_plugin/models/exams/sp_o2.dart';

/// 血氧
class SpO2DeviceWorker extends DeviceWorkerBase {
  SpO2DeviceWorker({
    required super.model,
    required super.mac,
  }) : super(type: DeviceTypes.SPO2);

  /// 测试值更新事件
  final valueUpdateEvent = FEventHandler<SpO2ExamValue>();

  /// 波形更新事件
  final pointsUpdateEvent = FEventHandler<List<int>>();

  /// 测量错误事件
  final errorEvent = FEventHandler<String>();

  @override
  void init() {
    super.init();

    injectStatusCallback(VDeviceEventStatus.EXAM_SPO2_SUCCESS, _onValue);
    injectStatusCallback(VDeviceEventStatus.EXAM_SPO2_POINTS, _onPoints);
    injectStatusCallback(
        VDeviceEventStatus.EXAM_SPO2PROBE_FALLOFF_ERROR, _onFalloffError);
  }

  void _onValue(Map<String, dynamic>? data) {
    final SpO2ExamData examData = SpO2ExamData.fromEventData(data!);
    log("Vaule updata; SpO2: ${examData.spO2}, Pulse: ${examData.pulse}");
    valueUpdateEvent.emit(this, examData);
  }

  void _onPoints(Map<String, dynamic>? data) {
    final SpO2ExamData examData = SpO2ExamData.fromEventData(data!);
    log("Points updata; Length: ${examData.points.length}");
    pointsUpdateEvent.emit(this, examData.points);
  }

  void _onFalloffError(Map<String, dynamic>? data) {
    const String msg =
        "${VDeviceEventStatus.EXAM_SPO2PROBE_FALLOFF_ERROR}|ProbeFalloff";
    log("Error: $msg");
    errorEvent.emit(this, msg);
  }
}
