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/error.dart';
import 'package:vnote_device_plugin/models/exams/sugar.dart';

/// 血糖
class SugarDeviceWorker extends DeviceWorkerBase {
  SugarDeviceWorker({
    required super.model,
    required super.mac,
  }) : super(type: DeviceTypes.SUGAR);

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

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

  /// 报警事件
  final warnEvent = FEventHandler<ExamError>();

  /// 状态变更事件
  final statusEvent = FEventHandler<ExamError>();

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

    injectStatusCallback(VDeviceEventStatus.EXAM_SUGAR_SUCCESS, _onSuccess);
    injectStatusCallback(VDeviceEventStatus.EXAM_SUGAR_ERROR, _onError);
    injectStatusCallback(VDeviceEventStatus.EXAM_MEASURE_SUGAR_WARN, _onWarn);
    injectStatusCallback(
        VDeviceEventStatus.EXAM_MEASURE_SUGAR_STATUS, _onStatus);
  }

  void _onSuccess(Map<String, dynamic>? data) {
    final SugarExamData examData = SugarExamData.fromEventData(data!);
    log("Result; SUGAR: ${examData.sugar}");
    successEvent.emit(this, examData);
  }

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

  void _onWarn(Map<String, dynamic>? data) {
    final ExamError model = ExamError.fromEventData(data!);
    model.code = "E${model.code}";
    log("Warn; CODE: ${model.code}, MSG: ${model.message}");
    warnEvent.emit(this, model);
  }

  void _onStatus(Map<String, dynamic>? data) {
    final ExamError model = ExamError.fromEventData(data!);
    log("Status; CODE: ${model.code}, MSG: ${model.message}");
    statusEvent.emit(this, model);
  }
}
