import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/flutter_flow/flutter_flow_model.dart';
import 'package:hub/pages/qr_code_page/qr_code_page_widget.dart';

import 'package:qr_flutter/qr_flutter.dart';

class QrCodePageModel extends FlutterFlowModel<QrCodePageWidget> {
  ///  Local state fields for this page.

  String? key;

  DateTime? time;
  bool isAccess = false;
  late final bool isFingerprint;
  late final String userDevUUID;
  late final VoidCallback? safeSetState;

  ///  State fields for stateful widgets in this page.

  final unfocusNode = FocusNode();

  @override
  void initState(BuildContext context) {
    initVariable();
  }

  Future<void> initVariable() async {
    isFingerprint =
        await StorageHelper().get(LocalsStorageKey.fingerprint.key) == 'true';
    userDevUUID =
        await StorageHelper().get(ProfileStorageKey.userDevUUID.key) ?? '';
    safeSetState?.call();
  }

  @override
  void dispose() {
    unfocusNode.dispose();
  }

  Uint8List assembleQRPacket(
      int direction, String identifier, String password) {
    List<int> packet = [direction];

    String paddedBadge = identifier.padLeft(30, '0');

    for (var i = 0; i < paddedBadge.length; i += 2) {
      packet.add(int.parse(paddedBadge.substring(i, i + 2), radix: 16));
    }

    DateTime now = DateTime.now();
    int year = now.year % 100;
    int month = now.month;
    int day = now.day;
    int hour = now.hour;
    int minute = now.minute;

    int sum = year + month + day + hour + minute;

    if (sum == int.parse('0D', radix: 16) ||
        sum == int.parse('0A', radix: 16)) {
      packet.add(int.parse('FF', radix: 16));
    } else {
      packet.add(sum);
    }

    String paddedPassword = password.length != 4 ? 'FFFF' : password;

    for (var i = 0; i < paddedPassword.length; i += 2) {
      packet.add(int.parse(paddedPassword.substring(i, i + 2), radix: 16));
    }

    int check = 0x00;

    for (var b in packet) {
      check ^= b;
    }

    if (check == int.parse('0D', radix: 16) ||
        check == int.parse('0A', radix: 16)) {
      packet.add(int.parse('FF', radix: 16));
    } else {
      packet.add(check);
    }

    return Uint8List.fromList(packet);
  }

  Uint8List hexStringToByteArray(String s) {
    int len = s.length;
    Uint8List data = Uint8List(len ~/ 2);
    for (int i = 0; i < len; i += 2) {
      data[i ~/ 2] =
          ((int.parse(s[i], radix: 16) << 4) + int.parse(s[i + 1], radix: 16));
    }
    return data;
  }

  String byteToHexa(Uint8List pDados) {
    return pDados
        .map((byte) => byte.toRadixString(16).padLeft(2, '0').toUpperCase())
        .join();
  }

  Future<String> byteToString(Uint8List bytes) async {
    return String.fromCharCodes(bytes);
  }

  Widget buildQrCode(
      {required int errorCorrectLevel,
      required double dimension,
      required String identifier,
      required String pass,
      required int direction}) {
    try {
      const Color backgroundColor = Colors.white;
      const Color foregroundColor = Colors.black;
      return QrImageView.withQr(
          qr: QrCode.fromUint8List(
              data: assembleQRPacket(direction, identifier, pass),
              errorCorrectLevel: errorCorrectLevel),
          size: dimension,
          padding: const EdgeInsets.all(10),
          backgroundColor: backgroundColor,
          foregroundColor: foregroundColor);
    } catch (e) {
      return Text("Erro ao gerar QR Code: ${e.toString()}");
    }
  }

  /// Action blocks.
  Future qrCodeEncoder(
    BuildContext context, {
    required String? key,
  }) async {}
}
