import 'dart:convert';
import 'dart:async';
import 'package:charset/charset.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:asreader_sdk4/asreader_sdk4.dart';
import 'package:asreader_sdk4_example/dataitem.dart';
import 'package:asreader_sdk4_example/more.dart';
import 'package:asreader_sdk4_example/LocalCache.dart';
import 'package:flutter_svprogresshud/flutter_svprogresshud.dart';

void main() => runApp(const MaterialApp(
      title: 'AsReader',
      home: MyApp(),
      debugShowCheckedModeBanner: false,
    ));

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    var home = const Scaffold(
      body: MainWidget(),
    );
    return home;
  }
}

class MainWidget extends StatefulWidget {
  const MainWidget({super.key});
  @override
  State<StatefulWidget> createState() => MainState();
}

class MainState extends State<MainWidget> {
  final _asreaderSdk4Plugin = AsreaderSdk4();
  static const iosCallPlatform = MethodChannel('asreader_sdk4');
  static const M24D = 'M24D';
  final cache = LocalCache();
  bool isBeep = false;
  bool isVibration = false;
  List<DataItem> listItems = [];
  Map<String, DataItem> map = {};
  int totalCount = 0;
  bool isConnect = false;
  String deviceName = 'Unknown Device';
  String connectStatus = 'UnPlugged';
  Set<int> selectedSet = {2};
  final List<bool> _typeSelecteds = [false, false];
  final List<bool> _selecteds = [false, false, false, false, false];

  String batteryImage = 'images/battery.png';
  bool connectTypeStatus = true;

  String bluetoothImage = 'images/bledis.png';
  Widget bluetoothIcon = const Icon(null);
  bool bluetoothStatus = false;

  Widget moreIcon = Image.asset(
    'images/settings.png',
    width: 25,
    height: 25,
    fit: BoxFit.cover,
  );
  late BuildContext mContext;
  List<String> listBluetooth = [];
  bool isPlugged = false;
  bool isBarcode = false;
  bool isRfid = false;
  bool isNfc = false;
  bool isDual = false;
  bool isLf = false;

  Color usbTextColor = Colors.blue;
  Color bleTextColor = Colors.black;

  Color barTextColor = Colors.grey;
  Color rfidTextColor = Colors.grey;
  Color nfcTextColor = Colors.grey;
  Color dualTextColor = Colors.grey;
  Color lfTextColor = Colors.grey;

  bool autoConnect = false;
  bool bottomStatus = false;
  int currentType = 0;
  bool canConnect = true;

  @override
  void initState() {
    super.initState();
    SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.dark);
    initPlatformState();
  }
  Future<void> initPlatformState() async {
    Future<dynamic> _handler(MethodCall methodCall) {
      print(
          'methodCall.method:${methodCall.method}, methodCall.arguments:${methodCall.arguments}');
      if (_asreaderSdk4Plugin.PLUGGED_STATUS == methodCall.method) {
        bool isPluged = methodCall.arguments['result'];
        print(
            'Main isPluged:$isPluged, methodCall.arguments:${methodCall.arguments}');
        plugged(isPluged);
      } else if (_asreaderSdk4Plugin.BATTERY_RECEIVED == methodCall.method) {
        int battery = methodCall.arguments['result'];
        print('battery:$battery, methodCall.arguments:${methodCall.arguments}');
        batteryReceived(battery);
      } else if (_asreaderSdk4Plugin.CONNECTED_STATUS == methodCall.method) {
        bool isConnected = methodCall.arguments['result'];
        print(
            'Main isConnected:$isConnected, methodCall.arguments:${methodCall.arguments}');
        connected(isConnected);
      } else if (_asreaderSdk4Plugin.RECEIVED_SCAN_DATA == methodCall.method) {
        Uint8List byteData = methodCall.arguments['result'];
        String epc = '';
        String pc = '';
        String type = '';
        Future<int> currentReaderMode = _asreaderSdk4Plugin.currentReaderMode();
        currentReaderMode.then((futureResult) {
          if (futureResult == 0) {
            type = 'BARCODE';
            ShiftJISDecoder shiftJisDecoder = const ShiftJISDecoder();
            epc = shiftJisDecoder.convert(byteData);
            if (epc == null || epc.isEmpty) {
              Utf8Decoder uft8Decoder = const Utf8Decoder();
              epc = uft8Decoder.convert(byteData);
            }
            if (epc == null || epc.isEmpty) {
              epc = String.fromCharCodes(byteData);
            }
            print('scan data type:$type, epc:$epc, pc:$pc,methodCall.arguments:${methodCall.arguments}');
            receivedData(type, epc, pc);
          } else if (futureResult == 1) {
            type = 'RFID';
            pc = byteData[0].toRadixString(16).padLeft(2, '0') + byteData[1].toRadixString(16).padLeft(2, '0');
            for (int i = 2; i<byteData.length; i++){
              epc = epc + byteData[i].toRadixString(16).padLeft(2, '0');
            }
            print('scan data type:$type, epc:$epc, pc:$pc,methodCall.arguments:${methodCall.arguments}');
            receivedData(type, epc, pc);
          } else if (futureResult == 2) {
            type = 'NFC';
            int nNFCDataLen = byteData[3] & 0xFF;
            int nTotalSize = nNFCDataLen + 4 + 3;
            int btSum = 0x00;
            for (int i = 0; i<nNFCDataLen+4+1; i++) {
              btSum = (btSum + (byteData[i] & 0xFF)) & 0xFF;
            }
            if(nTotalSize != byteData.length) {
              epc = 'Data Size Err';
            } else if(btSum != byteData[4 + nNFCDataLen + 1]) {
              epc = 'Check Sum Err';
            } else if(((byteData[0] & 0xFF) == 0x02)&&((byteData[4 + nNFCDataLen] & 0xFF) == 0x03)&&(nTotalSize== byteData.length)) {
              for(int i = 0; i<nNFCDataLen; i++){
                epc = epc + byteData[i+4].toRadixString(16).padLeft(2, '0');
              }
            } else {
              epc = 'Data Format Err';
            }
            print('scan data type:$type, epc:$epc, pc:$pc,methodCall.arguments:${methodCall.arguments}');
            receivedData(type, epc, pc);
          } else if (futureResult == 3) {
            Future<int> receiveDataType = _asreaderSdk4Plugin.receiveDataType();
            receiveDataType.then((futureResult) {
              if (futureResult == 0) {
                type = 'BARCODE';
                ShiftJISDecoder shiftJisDecoder = const ShiftJISDecoder();
                epc = shiftJisDecoder.convert(byteData);
                if (epc == null || epc.isEmpty) {
                  Utf8Decoder uft8Decoder = const Utf8Decoder();
                  epc = uft8Decoder.convert(byteData);
                }
                if (epc == null || epc.isEmpty) {
                  epc = String.fromCharCodes(byteData);
                }
                print('scan data type:$type, epc:$epc, pc:$pc,methodCall.arguments:${methodCall.arguments}');
                receivedData(type, epc, pc);
              } else if (futureResult == 1) {
                type = 'RFID';
                pc = byteData[0].toRadixString(16).padLeft(2, '0') + byteData[1].toRadixString(16).padLeft(2, '0');
                for (int i = 2; i<byteData.length; i++){
                  epc = epc + byteData[i].toRadixString(16).padLeft(2, '0');
                }
                print('scan data type:$type, epc:$epc, pc:$pc,methodCall.arguments:${methodCall.arguments}');
                receivedData(type, epc, pc);
              }
            });
          } else if (futureResult == 4) {
            type = 'RFID';
            epc = uint8ListToHexString(byteData);
            String natinalCode = '';
            String countryCode = '';
            String statusFlag = '';
            String animalIndicator = '';
            String reserved = '';
            Future<Map<String,String>> receivedMap = _asreaderSdk4Plugin.parseDataByProtocolType(byteData, 0);
            receivedMap.then((futureResult) {
              if (futureResult.containsKey('Key_FDBX_NationalCode')) {
                natinalCode = futureResult['Key_FDBX_NationalCode'].toString();
              }
              if (futureResult.containsKey('Key_FDBX_CountryCode')) {
                countryCode = futureResult['Key_FDBX_CountryCode'].toString();
              }
              if (futureResult.containsKey('Key_FDBX_StatusFlag')) {
                statusFlag = futureResult['Key_FDBX_StatusFlag'].toString();
              }
              if (futureResult.containsKey('Key_FDBX_AnimalIndicator')) {
                animalIndicator = futureResult['Key_FDBX_AnimalIndicator'].toString();
              }
              if (futureResult.containsKey('Key_FDBX_Reserved')) {
                reserved = futureResult['Key_FDBX_Reserved'].toString();
              }
              pc = natinalCode + countryCode + statusFlag + animalIndicator + reserved;
              print('scan data type:$type, epc:$epc, pc:$pc,methodCall.arguments:${methodCall.arguments}');
              receivedData(type, epc, pc);
            });
          }
        });
      } else if (_asreaderSdk4Plugin.SCANING_BLE_DEVICE == methodCall.method) {
        String name = methodCall.arguments['name'];
        print('scaning ble device name:$name, methodCall.arguments:${methodCall.arguments}');
        scanningBleDeive(name);
      } else if (_asreaderSdk4Plugin.SCAN_BLE_STATUS == methodCall.method) {
        String status = methodCall.arguments['status'];
        print('scan ble status:$status, methodCall.arguments:${methodCall.arguments}');
        scanBleStatus(status);
      } else if (_asreaderSdk4Plugin.RELEASED_TRIGGER_BUTTON == methodCall.method) {
        print('releasedTriggerButton, methodCall.arguments:${methodCall.arguments}');
        releasedTrigger();
      } else if (_asreaderSdk4Plugin.PUSHED_TRIGGER_BUTTON == methodCall.method) {
        print('pushedTriggerButton, methodCall.arguments:${methodCall.arguments}');
        pushTrigger();
      } else if (_asreaderSdk4Plugin.TRIGGER_STATUS == methodCall.method) {
        String status = methodCall.arguments['result'];
        print('checkTriggerStatus:$status, methodCall.arguments:${methodCall.arguments}');
        setState(() {
          Future.delayed(const Duration(milliseconds:50), () {
            setState(() {
              deviceName = status;
            });
          });
        });
      }
      return Future.value('success');
    }

    iosCallPlatform.setMethodCallHandler(_handler);
    try {
      _asreaderSdk4Plugin.showPrintNSLog(true);
      _asreaderSdk4Plugin.setTriggerMode(true);
      String platformVersion = await _asreaderSdk4Plugin.getPlatformVersion() ??
          'Unknown platform version';
      print('platformVersion: $platformVersion');
    } on PlatformException {
      print('Failed to get platform version.');
    }
  }

  @override
  Widget build(BuildContext context) {
    mContext = context;
    ListView listView;
    listView = ListView.builder(
        shrinkWrap: true,
        itemCount: listItems.length,
        itemBuilder: (context, index) {
          final listItem = listItems[index];
          return Column(
            children: <Widget>[
              getListTile(dataType(listItem.type), listItem.epc, listItem.pc,
                  listItem.count),
              const Divider(height: 1, color: Colors.black38), //Divider
            ],
          );
        });

    var boldGrayContainer = Container(
      color: Colors.black54,
      padding: const EdgeInsets.fromLTRB(15, 7, 15, 7),
      height: 5,
    );

    var upContainer = Container(
      color: Colors.white,
      padding: const EdgeInsets.fromLTRB(30, 7, 110, 7),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Expanded(
            child: Text(
              '$totalCount tags',
              style: const TextStyle(
                  height: 1.5,
                  color: Colors.black,
                  fontSize: 14.0,
                  fontWeight: FontWeight.w400,
                  backgroundColor: Colors.white38),
              textAlign: TextAlign.left,
            ),
          ),
          Expanded(
            child: Text(
              connectStatus,
              style: const TextStyle(
                  height: 1.5,
                  color: Colors.black,
                  fontSize: 16.0,
                  fontWeight: FontWeight.w400,
                  backgroundColor: Colors.white38),
              textAlign: TextAlign.left,
            ),
          ),
        ],
      ),
    );

    var grayContainer = Container(
      color: Colors.black54,
      padding: const EdgeInsets.fromLTRB(15, 7, 15, 7),
      height: 1,
    );

    var connectTypeContainer = Container(
      color: Colors.white,
      margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Image.asset(
            batteryImage,
            width: 30,
            height: 15,
            fit: BoxFit.cover,
          ),
          Visibility(
            visible: connectTypeStatus,
            child: ToggleButtons(
              isSelected: _typeSelecteds,
              color: Colors.white,
              fillColor: Colors.white,
              splashColor: Colors.white,
              borderWidth: 2,
              borderRadius: BorderRadius.circular(10),
              borderColor: Colors.black,
              selectedBorderColor: Colors.black,
              direction: Axis.horizontal,
              children: <Widget>[
                Text(
                  'USB',
                  style: TextStyle(
                      height: 0.5,
                      color: usbTextColor,
                      fontSize: 15.0,
                      fontWeight: FontWeight.w400,
                      backgroundColor: Colors.transparent),
                  textAlign: TextAlign.left,
                ),
                Text(
                  'BLE',
                  style: TextStyle(
                      height: 0.5,
                      color: bleTextColor,
                      fontSize: 15.0,
                      fontWeight: FontWeight.w400,
                      backgroundColor: Colors.transparent),
                  textAlign: TextAlign.left,
                ),
              ],
              onPressed: (index) {
                setState(() {
                  if (index == 0) {
                    _usbType();
                  } else if (index == 1) {
                    _bluetoothType();
                  }
                });
              },
            ),
          ),
          IconButton(
            icon: bluetoothIcon,
            onPressed: () {
              if (bluetoothStatus) {
                _bluetooth();
              }
            },
          ),
        ],
      ),
    );

    var deviceTypeContainer = Container(
      color: Colors.white,
      margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          ToggleButtons(
            isSelected: _selecteds,
            color: Colors.white,
            fillColor: Colors.white,
            splashColor: Colors.white,
            borderWidth: 2,
            borderRadius: BorderRadius.circular(10),
            borderColor: Colors.black,
            selectedBorderColor: Colors.black,
            direction: Axis.horizontal,
            children: <Widget>[
              Text(
                'BAR',
                style: TextStyle(
                    height: 0.5,
                    color: barTextColor,
                    fontSize: 15.0,
                    fontWeight: FontWeight.w400,
                    backgroundColor: Colors.transparent),
                textAlign: TextAlign.left,
              ),
              Text(
                'RFID',
                style: TextStyle(
                    height: 0.5,
                    color: rfidTextColor,
                    fontSize: 15.0,
                    fontWeight: FontWeight.w400,
                    backgroundColor: Colors.transparent),
                textAlign: TextAlign.left,
              ),
              Text(
                'NFC',
                style: TextStyle(
                    height: 0.5,
                    color: nfcTextColor,
                    fontSize: 15.0,
                    fontWeight: FontWeight.w400,
                    backgroundColor: Colors.transparent),
                textAlign: TextAlign.left,
              ),
              Text(
                'DUAL',
                style: TextStyle(
                    height: 0.5,
                    color: dualTextColor,
                    fontSize: 15.0,
                    fontWeight: FontWeight.w400,
                    backgroundColor: Colors.transparent),
                textAlign: TextAlign.left,
              ),
              Text(
                'LF',
                style: TextStyle(
                    height: 0.5,
                    color: lfTextColor,
                    fontSize: 15.0,
                    fontWeight: FontWeight.w400,
                    backgroundColor: Colors.transparent),
                textAlign: TextAlign.left,
              ),
            ],
            onPressed: (index) {
              setState(() {
                if (index == 0) {
                  if (isPlugged && isBarcode && currentType != 0) {
                    currentType = 0;
                    isConnect = false;
                    connect(isConnect);
                    barTextColor = Colors.blue;
                    if (isRfid) {
                      rfidTextColor = Colors.black;
                    } else {
                      rfidTextColor = Colors.grey;
                    }
                    if (isNfc) {
                      nfcTextColor = Colors.black;
                    } else {
                      nfcTextColor = Colors.grey;
                    }
                    if (isDual) {
                      dualTextColor = Colors.black;
                    } else {
                      dualTextColor = Colors.grey;
                    }
                    if (isLf) {
                      lfTextColor = Colors.black;
                    } else {
                      lfTextColor = Colors.grey;
                    }
                  }
                } else if (index == 1) {
                  if (isPlugged && isRfid && currentType != 1) {
                    currentType = 1;
                    isConnect = false;
                    connect(isConnect);
                    rfidTextColor = Colors.blue;
                    if (isBarcode) {
                      barTextColor = Colors.black;
                    } else {
                      barTextColor = Colors.grey;
                    }
                    if (isNfc) {
                      nfcTextColor = Colors.black;
                    } else {
                      nfcTextColor = Colors.grey;
                    }
                    if (isDual) {
                      dualTextColor = Colors.black;
                    } else {
                      dualTextColor = Colors.grey;
                    }
                    if (isLf) {
                      lfTextColor = Colors.black;
                    } else {
                      lfTextColor = Colors.grey;
                    }
                  }
                } else if (index == 2) {
                  if (isPlugged && isNfc && currentType != 2) {
                    currentType = 2;
                    isConnect = false;
                    connect(isConnect);
                    nfcTextColor = Colors.blue;
                    if (isBarcode) {
                      barTextColor = Colors.black;
                    } else {
                      barTextColor = Colors.grey;
                    }
                    if (isRfid) {
                      rfidTextColor = Colors.black;
                    } else {
                      rfidTextColor = Colors.grey;
                    }
                    if (isDual) {
                      dualTextColor = Colors.black;
                    } else {
                      dualTextColor = Colors.grey;
                    }
                    if (isLf) {
                      lfTextColor = Colors.black;
                    } else {
                      lfTextColor = Colors.grey;
                    }
                  }
                } else if (index == 3) {
                  if (isPlugged && isDual && currentType != 3) {
                    currentType = 3;
                    isConnect = false;
                    connect(isConnect);
                    dualTextColor = Colors.blue;
                    if (isBarcode) {
                      barTextColor = Colors.black;
                    } else {
                      barTextColor = Colors.grey;
                    }
                    if (isRfid) {
                      rfidTextColor = Colors.black;
                    } else {
                      rfidTextColor = Colors.grey;
                    }
                    if (isNfc) {
                      nfcTextColor = Colors.black;
                    } else {
                      nfcTextColor = Colors.grey;
                    }
                    if (isLf) {
                      lfTextColor = Colors.black;
                    } else {
                      lfTextColor = Colors.grey;
                    }
                  }
                } else if (index == 4) {
                  if (isPlugged && isLf && currentType != 4) {
                    currentType = 4;
                    isConnect = false;
                    connect(isConnect);
                    lfTextColor = Colors.blue;
                    if (isBarcode) {
                      barTextColor = Colors.black;
                    } else {
                      barTextColor = Colors.grey;
                    }
                    if (isRfid) {
                      rfidTextColor = Colors.black;
                    } else {
                      rfidTextColor = Colors.grey;
                    }
                    if (isNfc) {
                      nfcTextColor = Colors.black;
                    } else {
                      nfcTextColor = Colors.grey;
                    }
                    if (isDual) {
                      dualTextColor = Colors.black;
                    } else {
                      dualTextColor = Colors.grey;
                    }
                  }
                }
              });
            },
          )
        ],
      ),
    );

    var boldGrayContainer2 = Container(
      color: Colors.black54,
      padding: const EdgeInsets.fromLTRB(15, 7, 15, 7),
      margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
      height: 5,
    );
    var boldGrayContainer3 = Container(
      color: Colors.black54,
      padding: const EdgeInsets.fromLTRB(15, 7, 15, 7),
      height: 5,
    );
    var bottomContainer = Container(
      color: Colors.white,
      child: Visibility(
        visible: bottomStatus,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Switch(
              value: isConnect,
              onChanged: (bool value) {
                setState(() {
                  if (canConnect) {
                    isConnect = value;
                    connect(isConnect);
                  }
                });
              },
            ),
            ElevatedButton(
              onPressed: _startScan,
              child: const Text('Read'),
            ),
            ElevatedButton(
              onPressed: _stopScan,
              child: const Text('Stop'),
            ),
            ElevatedButton(
              onPressed: _clear,
              child: const Text('Clear'),
            ),
          ],
        ),
      ),
    );
    return Scaffold(
      appBar: AppBar(
        title: Text(deviceName),
        backgroundColor: Colors.white,
        actions: <Widget>[
          IconButton(
            icon: moreIcon,
            onPressed: () async {
              final result = await Navigator.push(context,
                  MaterialPageRoute(builder: (context) => MoreWidget()));
              if (result != null) {
                  if (result == 'NO') {
                    plugged(false);
                  }
              }
              initPlatformState();
            },
          ),
        ],
      ),
      body: Container(
        color: Colors.white,
        child: Column(
          children: <Widget>[
              boldGrayContainer,
              upContainer,
              grayContainer,
              const SizedBox(height: 5),
              connectTypeContainer,
              const SizedBox(height: 5),
              deviceTypeContainer,
              const SizedBox(height: 5),
              boldGrayContainer2,
              Expanded(
                child: listView,
              ),
              boldGrayContainer3,
              bottomContainer,
            ],
          ),
        ),
      );
  }

  Widget getListTile(String type, String epc, String pc, int count) {
    return Container(
      padding: const EdgeInsets.all(5.0),
      child: ListTile(
        onTap: () {},
        leading: Image.asset(
          type,
          width: 30,
          height: 30,
          fit: BoxFit.cover,
        ),
        trailing: Text(
          count.toString(),
          style: const TextStyle(color: Colors.black54),
        ),
        title: Text(
          epc,
          style: const TextStyle(color: Colors.black),
        ),
        subtitle: Text(
          pc,
          style: const TextStyle(color: Colors.black),
        ),
      ),
    );
  }

  Future<void> _startScan() async {
    print('_startScan start');
    try {
      if (barTextColor == Colors.blue) {
        _asreaderSdk4Plugin.startBarcodeScan(0, 0);
      } else if (rfidTextColor == Colors.blue) {
        _asreaderSdk4Plugin.startScan(0, 0, 0);
      } else if (nfcTextColor == Colors.blue) {
        _asreaderSdk4Plugin.startNFCScan();
      } else if (dualTextColor == Colors.blue) {
        _asreaderSdk4Plugin.startBarcodeScan(0, 0);
        _asreaderSdk4Plugin.startScan(0, 0, 0);
      } else if (lfTextColor == Colors.blue) {
        _asreaderSdk4Plugin.startLfScan(0, 0, 0);
      }
    } on PlatformException {
      print('Failed to start scan.');
    }
    print('_startScan end');
  }

  Future<void> _stopScan() async {
    print('_stopScan start');
    try {
      if (barTextColor == Colors.blue) {
        _asreaderSdk4Plugin.stopBarcodeScan();
      } else if (rfidTextColor == Colors.blue) {
        _asreaderSdk4Plugin.stopRfidScan();
      } else if (nfcTextColor == Colors.blue) {
        _asreaderSdk4Plugin.stopNFCScan();
      } else if (dualTextColor == Colors.blue) {
        _asreaderSdk4Plugin.stopBarcodeScan();
        _asreaderSdk4Plugin.stopRfidScan();
      } else if (lfTextColor == Colors.blue) {
        _asreaderSdk4Plugin.stopLfScan();
      }
    } on PlatformException {
      print('Failed to stop scan.');
    }
    print('_stopScan end');
  }

  void _clear() {
    print('_clear start');
    listItems.clear();
    map.clear();
    totalCount = 0;
    setState(() {});
    print('_clear end');
  }

  void _usbType() {
    print('_usbType start');
    setState(() {
      usbTextColor = Colors.blue;
      bleTextColor = Colors.black;
      bluetoothIcon = const Icon(null);
      const Icon(null);
      bluetoothIcon = const Icon(null);
      bluetoothStatus = false;
      connectTypeStatus = false;
      bottomStatus = false;
      _asreaderSdk4Plugin.setConnectionType(0);
      Future.delayed(const Duration(seconds:5), () {
        setState(() {
          setConnectTypeStatus();
        });
      });
    });
    print('_usbType end');
  }

  void _bluetoothType() {
    print('_bluetoothType start');
    setState(() {
      usbTextColor = Colors.black;
      bleTextColor = Colors.blue;
      deviceName = 'Unknown Device';
      connectStatus = 'UnPlugged';
      batteryImage = 'images/battery.png';
      moreIcon = const Icon(null);
      bluetoothIcon = const Icon(null);
      connectTypeStatus = false;
      bottomStatus = false;
      _asreaderSdk4Plugin.setConnectionType(1);
      if (usbTextColor == Colors.black && bleTextColor == Colors.blue) {
        bluetoothImage = 'images/bledis.png';
        bluetoothIcon = Image.asset(
          bluetoothImage,
          width: 40,
          height: 40,
          fit: BoxFit.cover,
        );
        bluetoothStatus = true;
      }
      Future.delayed(const Duration(seconds:5), () {
        setState(() {
          setConnectTypeStatus();
        });
      });
    });
    print('_bluetoothType end');
  }
  Future<void> _bluetooth() async {
    print('_bluetooth start');
    setState(() {
      listBluetooth.clear();
      Future<bool> status = _asreaderSdk4Plugin.isOpened();
      status.then((futureResult) {
        if (futureResult == false) {
          print('_bluetooth startBleScan');
          _asreaderSdk4Plugin.startBleScan();
        } else {
          print('_bluetooth disConnectBLE');
          _asreaderSdk4Plugin.disConnectBLE();
        }
      });
    });
    print('_bluetooth end');
  }
  void setConnectTypeStatus() {
    print('setConnectTypeStatus start');
    connectTypeStatus = true;
    print('setConnectTypeStatus end');
  }
  void plugged(bool isPluged) {
    setState(() {
      isPlugged = isPluged;
      if (isPluged) {
        Future<bool> isPower = _asreaderSdk4Plugin.isEnginePowerAlwaysOn();
        isPower.then((futureResult) {
          if (futureResult) {
            canConnect = false;
          } else {
            canConnect = true;
          }
        });
        usbTextColor = Colors.blue;
        bleTextColor = Colors.black;
        if (usbTextColor == Colors.blue && bleTextColor == Colors.black) {
          bluetoothIcon = const Icon(null);
          bluetoothStatus = false;
        } else if (usbTextColor == Colors.black && bleTextColor == Colors.blue) {
          bluetoothImage = 'images/blecon.png';
          bluetoothIcon = Image.asset(
            bluetoothImage,
            width: 40,
            height: 40,
            fit: BoxFit.cover,
          );
          bluetoothStatus = true;
        }
        bottomStatus = true;
        Future<String> deviceNameString = _asreaderSdk4Plugin.deviceName();
        deviceNameString.then((futureResult) {
          deviceName = futureResult;
        });
        Future<bool> isPowerOn = _asreaderSdk4Plugin.isPowerOn();
        isPowerOn.then((futureResult) {
           if (futureResult) {
             connectStatus = 'Connected';
           } else {
             connectStatus = 'Plugged';
           }
        });
        Future<bool> isSuppportBarcode = _asreaderSdk4Plugin.isSupportType(0);
        isSuppportBarcode.then((futureResult) {
          if (futureResult) {
            isBarcode = true;
          } else {
            isBarcode = false;
          }
          print('barcode = $futureResult');
        });
        Future<bool> isSuppportRfid = _asreaderSdk4Plugin.isSupportType(1);
        isSuppportRfid.then((futureResult) {
          if (futureResult) {
            isRfid = true;
          } else {
            isRfid = false;
          }
          print('isRfid = $futureResult');
        });
        Future<bool> isSuppportNfc = _asreaderSdk4Plugin.isSupportType(2);
        isSuppportNfc.then((futureResult) {
          if (futureResult) {
            isNfc = true;
          } else {
            isNfc = false;
          }
          print('isNfc = $futureResult');
        });
        Future<bool> isSuppportDual = _asreaderSdk4Plugin.dualSameTime();
        isSuppportDual.then((futureResult) {
          if (futureResult) {
            isDual = true;
          } else {
            isDual = false;
          }
          print('isDual = $futureResult');
        });
        Future<bool> isSuppportLf = _asreaderSdk4Plugin.isSupportType(4);
        isSuppportLf.then((futureResult) {
          if (futureResult) {
            isLf = true;
          } else {
            isLf = false;
          }
          print('isLf = $futureResult');
        });
        Future.delayed(const Duration(milliseconds:500), () {
          setState(() {
            try {
              autoConnect = true;
              if (isLf) {
                currentType =  4;
              }
              if (isDual) {
                currentType =  3;
              }
              if (isNfc) {
                currentType =  2;
              }
              if (isRfid) {
                currentType =  1;
              }
              if (isBarcode) {
                currentType =  0;
              }
              if (currentType == 0) {
                barTextColor = Colors.blue;
                rfidTextColor = Colors.grey;
                nfcTextColor = Colors.grey;
                dualTextColor = Colors.grey;
                lfTextColor = Colors.grey;
              } else if (currentType == 1) {
                barTextColor = Colors.grey;
                rfidTextColor = Colors.blue;
                nfcTextColor = Colors.grey;
                dualTextColor = Colors.grey;
                lfTextColor = Colors.grey;
              } else if (currentType == 2) {
                barTextColor = Colors.grey;
                rfidTextColor = Colors.grey;
                nfcTextColor = Colors.blue;
                dualTextColor = Colors.grey;
                lfTextColor = Colors.grey;
              } else if (currentType == 3) {
                barTextColor = Colors.grey;
                rfidTextColor = Colors.grey;
                nfcTextColor = Colors.grey;
                dualTextColor = Colors.blue;
                lfTextColor = Colors.grey;
              } else if (currentType == 4) {
                barTextColor = Colors.grey;
                rfidTextColor = Colors.grey;
                nfcTextColor = Colors.grey;
                dualTextColor = Colors.grey;
                lfTextColor = Colors.blue;
              }
              _asreaderSdk4Plugin.setReaderPower(
                  true, isBeep, isVibration, true, true, true, currentType);
            } on PlatformException {
              print('Failed to set reader power.');
            }
            // getRFModule();
          });
        });
      } else {
        if (usbTextColor == Colors.blue && bleTextColor == Colors.black) {
          bluetoothIcon = const Icon(null);
          bluetoothStatus = false;
        } else if (usbTextColor == Colors.black && bleTextColor == Colors.blue) {
          bluetoothImage = 'images/bledis.png';
          bluetoothIcon = Image.asset(
            bluetoothImage,
            width: 40,
            height: 40,
            fit: BoxFit.cover,
          );
          bluetoothStatus = true;
        }
        moreIcon = const Icon(null);
        deviceName = 'Unknown Device';
        connectStatus = 'UnPlugged';
        batteryImage = 'images/battery.png';
        isConnect = false;
        bottomStatus = false;
        barTextColor = Colors.grey;
        rfidTextColor = Colors.grey;
        nfcTextColor = Colors.grey;
        dualTextColor = Colors.grey;
        lfTextColor = Colors.grey;
        isBarcode = false;
        isRfid = false;
        isNfc = false;
        isDual = false;
        isLf = false;
      }
    });
  }

  void batteryReceived(int battery) {
    setState(() {
      int nVal = 0;
      if (battery > 95) {
        nVal = 4;
      } else if (battery > 70) {
        nVal = 3;
      } else if (battery > 45) {
        nVal = 2;
      } else if (battery > 20) {
        nVal = 1;
      } else {
        nVal = 0;
      }
      batteryImage = 'images/bat_normal_$nVal.png';
    });
  }

  void connected(bool isConnected) {
    setState(() {
      Future<bool> isPower = _asreaderSdk4Plugin.isEnginePowerAlwaysOn();
      isPower.then((futureResult) {
        if (futureResult) {
          canConnect = false;
        } else {
          canConnect = true;
        }
      });
      if (isConnected) {
        moreIcon = Image.asset(
          'images/settings.png',
          width: 25,
          height: 25,
          fit: BoxFit.cover,
        );
        connectStatus = 'Connected';
        isConnect = true;
        setBeepAndVibration();
        if (isBarcode) {
          barTextColor = Colors.black;
        } else {
          barTextColor = Colors.grey;
        }
        if (isRfid) {
          rfidTextColor = Colors.black;
        } else {
          rfidTextColor = Colors.grey;
        }
        if (isNfc) {
          nfcTextColor = Colors.black;
        } else {
          nfcTextColor = Colors.grey;
        }
        if (isDual) {
          dualTextColor = Colors.black;
        } else {
          dualTextColor = Colors.grey;
        }
        if (isLf) {
          lfTextColor = Colors.black;
        } else {
          lfTextColor = Colors.grey;
        }
        if (currentType == 0) {
          barTextColor = Colors.blue;
        } else if (currentType == 1) {
          rfidTextColor = Colors.blue;
        } else if (currentType == 2) {
          nfcTextColor = Colors.blue;
        } else if (currentType == 3) {
          dualTextColor = Colors.blue;
        } else if (currentType == 4) {
          lfTextColor = Colors.blue;
        }
        Future<String> deviceNameString = _asreaderSdk4Plugin.deviceName();
        deviceNameString.then((futureResult) {
          if (futureResult.contains('ASR-M30S')) {
            _asreaderSdk4Plugin.setContinuousMode(true);
            currentType = 1;
            barTextColor = Colors.grey;
            rfidTextColor = Colors.blue;
            nfcTextColor = Colors.grey;
            dualTextColor = Colors.grey;
            lfTextColor = Colors.grey;
          }
          if (futureResult.contains('025S')) {
            currentType = 0;
            barTextColor = Colors.blue;
            rfidTextColor = Colors.grey;
            nfcTextColor = Colors.grey;
            dualTextColor = Colors.grey;
            lfTextColor = Colors.grey;
          }
        });
      } else {
        moreIcon = const Icon(null);
        connectStatus = 'Disconnected';
        isConnect = false;
      }
    });
  }

  void connect(bool connect) {
    setState(() {
      try {
        autoConnect = false;
        _asreaderSdk4Plugin.setReaderPower(
            connect, isBeep, isVibration, true, true, true, currentType);
      } on PlatformException {
        print('Failed to connect.');
      }
    });
  }

  String dataType(String type) {
    if (type == 'RFID') {
      return 'images/icon_rfid.png';
    } else if (type == 'BARCODE') {
      return 'images/icon_barcode.png';
    } else if (type == 'NFC') {
      return 'images/icon_nfc.png';
    } else {
      return 'images/icon_rfid.png';
    }
  }
  void receivedData(String type, String epc, String pc) {
    setState(() {
      if (map.containsKey(epc)) {
        DataItem item = map[epc]!;
        item.count = item.count + 1;
        map.update(epc, (value) => item);
      } else {
        DataItem item = DataItem(type, epc, pc, 1);
        map[epc] = item;
        listItems.add(item);
      }
      totalCount = totalCount + 1;
    });
  }
  void setBeepAndVibration() async {
    isBeep = await cache.getBeep();
    isVibration = await cache.getVibration();
    _asreaderSdk4Plugin.setBeep(isBeep, isVibration, true, true);
  }
  void showAlertDialog(BuildContext context, String title, String message) {
    Widget okButton = ElevatedButton(
      child: const Text('OK'),
      onPressed: () {
        Navigator.of(context).pop();
      },
    );
    AlertDialog alert = AlertDialog(
      title: Text(title),
      content: Text(message),
      actions: [
        okButton,
      ],
    );
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
  void showAlertDialogWithData(BuildContext context, String title, String message, List<String> dataItems) {
    List<Widget> buttons = [];
    for (String title in dataItems) {
      Widget button = ElevatedButton(
        child: Text(title),
        onPressed: () {
          print('_bluetooth connectBLE = $title');
          _asreaderSdk4Plugin.connectBLE(title);
          Navigator.of(context).pop();
        },
      );
      buttons.add(button);
    }
    Widget okButton = ElevatedButton(
      child: const Text('OK'),
      onPressed: () {
        Navigator.of(context).pop();
      },
    );
    buttons.add(okButton);
    AlertDialog alert = AlertDialog(
      title: Text(title),
      content: Text(message),
      actions: buttons,
    );
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
  void scanningBleDeive(String name) {
    listBluetooth.add(name);
  }
  void scanBleStatus(String status) {
    setState(() {
      if (status == '0') {
        SVProgressHUD.show(status: 'Searching for device.');
      }
      if (status == '1') {
        SVProgressHUD.dismiss();
        if (listBluetooth.isNotEmpty) {
          showAlertDialogWithData(mContext, 'AsReader connection',
              'Please select a searched device below', listBluetooth);
        } else {
          showAlertDialog(
              mContext, 'No reader found.', 'Check the power of the reader.');
        }
      }
    });
  }
  String uint8ListToHexString(Uint8List list) {
    return list.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join('');
  }
  void releasedTrigger() {
    setState(() {
      deviceName = 'Custom TriggerDownUp';
      Future<String> deviceNameString = _asreaderSdk4Plugin.deviceName();
      deviceNameString.then((futureResult) {
        if (futureResult.contains(M24D)) {
          _asreaderSdk4Plugin.stopBarcodeScan();
        }
      });
    });
  }
  void pushTrigger() {
    setState(() {
      deviceName = 'Custom TriggerDown';
      Future<String> deviceNameString = _asreaderSdk4Plugin.deviceName();
      deviceNameString.then((futureResult) {
        if (futureResult.contains(M24D)) {
          _asreaderSdk4Plugin.startBarcodeScan(0, 0);
        }
      });
    });
  }
}
