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/urine.dart';
import 'package:vnote_device_plugin/vnote_device_plugin_platform_interface.dart';

/// 尿液
class UrineDeviceWorker extends DeviceWorkerBase {
  UrineDeviceWorker({
    required super.model,
    required super.mac,
  }) : super(type: DeviceTypes.URINE);

  /// 测量成功事件
  final successEvent = FEventHandler<UrineExamData>();

  /// 测量失败事件
  final errorEvent = FEventHandler<String>();

  /// 测量无结果事件
  final noResultEvent = FEventHandler<void>();

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

    injectStatusCallback(VDeviceEventStatus.EXAM_URINE_SUCCESS, _onSuccess);
    injectStatusCallback(VDeviceEventStatus.EXAM_URINE_ERROR, _onError);
    injectStatusCallback(VDeviceEventStatus.EXAM_URINE_NO_RESULT, _onNoResult);
  }

  /// 尿酸自动测试
  Future<void> autoTest() async {
    log("urine AUTO_TEST");
    await VnoteDevicePluginPlatform.instance.callAction(
      "AUTO_TEST",
      {
        "MODEL": model,
      },
    );
  }

  void _onSuccess(Map<String, dynamic>? data) {
    final UrineExamData examData = UrineExamData.fromEventData(data!);
    log("Result; LEU: ${examData.leu}, BLD: ${examData.bld}, NIT: ${examData.nit}, KET: ${examData.ket}");
    successEvent.emit(this, examData);
  }

  void _onError(Map<String, dynamic>? data) {
    final String msg = data!["MSG"] ?? "ERROR";
    log("Error: $msg");
    errorEvent.emit(this, msg);
  }

  void _onNoResult(Map<String, dynamic>? data) {
    log("NoResult");
    noResultEvent.emit(this, null);
  }
}
