import 'dart:convert';

import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';

import '../../models/finger_print_info.dart';
import '../constants/app_contants.dart';
import '../local_stoarge/app_storage.dart';
import 'SessionCache.dart';
// import 'package:local_auth/local_auth.dart';


class FingerPrintController {
  LocalAuthentication _localAuth = LocalAuthentication();
  RxBool isFingerPrintExistInDB = false.obs;
  RxBool isFingerprintSupported = false.obs;

  FingerPrintController() {
    _localAuth = LocalAuthentication();
    checkFingerprintSupport();
    checkIfExistDB();
  }

  Future<void> checkIfExistDB() async {
    String info = await AppStorage.getString(AppConstants.IS_FINGER_PRINT_ENABLED, fallback: "");
    isFingerPrintExistInDB.value = info.isNotEmpty;
  }

  Future<void> authenticate(Function(bool status)? callback, bool saveToDB) async {
    try {
      bool authenticated = await _localAuth.authenticate(
        localizedReason: 'Authenticate to access the app',
        options: const AuthenticationOptions(
          stickyAuth: true,
          biometricOnly: true,
          useErrorDialogs: true,
        ),
      );
      if (authenticated) {
        if (saveToDB) {
          FingerPrintInfo fingerPrintInfo = FingerPrintInfo();
          fingerPrintInfo.porOrgacode = SessionCache.instance.userInfo.porOrgacode;
          fingerPrintInfo.channelCode = SessionCache.instance.userInfo.channelCode;
          fingerPrintInfo.cmpUserId = SessionCache.instance.userInfo.cmpUserId;
          fingerPrintInfo.cmpCustpassword = SessionCache.instance.userInfo.cmpCustpassword;
          await AppStorage.putString(AppConstants.IS_FINGER_PRINT_ENABLED, jsonEncode(fingerPrintInfo.toMap()));
          isFingerPrintExistInDB.value = true;
          isFingerprintSupported.value = true;
        }
        if (callback != null) {
          callback(true);
        }
      } else {
        if (callback != null) {
          callback(false);
        }
      }
    } catch (e) {
      print(e);
    }
  }

  Future<void> checkFingerprintSupport() async {
    isFingerprintSupported.value = await _localAuth.isDeviceSupported();
  }

  Future<void> clearFromDB() async {
    await AppStorage.putString(AppConstants.IS_FINGER_PRINT_ENABLED, "");
    isFingerPrintExistInDB.value = false;
  }
}
