import 'package:mypoint_flutter_app/networking/restful_api_request.dart';

import '../../base/restful_api_viewmodel.dart';
import '../../permission/biometric_manager.dart';
import '../../preference/data_preference.dart';

class SettingViewModel extends RestfulApiViewModel {
  bool biometricEnabled = false;

  Future<bool> loadBiometricStatus() async {
    final phone = DataPreference.instance.phone;
    if (phone != null) {
      final token = await DataPreference.instance.getBioToken(phone) ?? "";
      biometricEnabled = token.isNotEmpty;
    } else {
      biometricEnabled = false;
    }
    return biometricEnabled;
  }

  Future<bool> toggleBiometric(bool enable) async {
    final phone = DataPreference.instance.phone;
    if (phone == null) return biometricEnabled;
    final canCheckBiometrics = BiometricManager().canCheckBiometrics();
    if (!(await canCheckBiometrics)) {
      return biometricEnabled;
    }
    final didAuthenticate = BiometricManager().authenticateBiometric();
    if (!(await didAuthenticate)) return biometricEnabled;

    showLoading();
    if (enable) {
      client.registerBiometric().then((value) {
        final token = value.data?.bioToken ?? "";
        DataPreference.instance.saveBioToken(token);
        hideLoading();
        return true;
      });
    } else {
      client.unRegisterBiometric().then((value) {
        DataPreference.instance.clearBioToken(phone!);
        hideLoading();
        return false;
      });
    }
    return enable;
  }
}
