import 'dart:async';

import 'package:anchor_collect_flutter/utils/empty_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import '../controllers/ble_service.dart';

typedef void EventCallback(args, args2);

class RfidPlugin {
  static const MethodChannel _methodChannel = MethodChannel('flutter_rfid_plugin');

  static const EventChannel _eventChannel = EventChannel('flutter_rfid_plugin/event');

  static EventCallback? _callback;

  late StreamSubscription<dynamic> _streamSubscription;

  static String rfidTagTemp = '';

  RfidPlugin() {
    _streamSubscription = _eventChannel.receiveBroadcastStream().listen((event) async {
      final Map<dynamic, dynamic> map = event;
      switch (map['key']) {
        case 'BluetoothData':
          await BleService.to.writeData(map['BluetoothData']);
          break;
        case 'InventoryData':
          checkInventory(map['value'].toString());
          break;
      }
    }, onError: errorEventListen, onDone: doneEventListen);
  }

  static Future<void> initRfid() async {
    await _methodChannel.invokeMethod('init_rfid');
  }

  static Future<String> getVersion() async {
    String version = await _methodChannel.invokeMethod('get_version');
    return version;
  }

  static Future<void> startInventory(EventCallback callback) async {
    _callback = callback;
    rfidTagTemp = '';
    await _methodChannel.invokeMethod('start_inventory');
  }

  static Future<void> stopInventory() async {
    await _methodChannel.invokeMethod('stop_inventory');
  }

  static Future<void> pushRemoteRFIDData(List<int> readData) async {
    // List<int> readData = await BleService.to.readData();
    Map params = {
      "value":readData,
    };
    await _methodChannel.invokeMethod('push_data', params);
  }

  errorEventListen(Object obj) {
    final Object e = obj;
    if (kDebugMode) {
      print("错误打印为------$obj");
    }
    throw e;
  }

  doneEventListen() {
    if (kDebugMode) {
      print("flutter响应完成------");
    }
  }

  checkInventory(String rfidTag) {
    if (!EmptyUtils.isStrNotEmpty(rfidTagTemp)) {
      rfidTagTemp = rfidTag;
      List<String> rfids = rfidTag.split(',');
      _callback!(rfids[0] ?? "", rfids[1] ?? "");
    }
  }

}
