import 'package:credit_card_scanner/credit_card_scanner.dart';
import 'package:flutter/cupertino.dart';
import 'package:permission_handler/permission_handler.dart';

Future<void> scanCard(
  BuildContext context,
  TextEditingController cardNumberController,
  TextEditingController cardExpirationDateController,
) async {
  PermissionStatus permissionStatus = await _getCameraPermission();

  if (permissionStatus == PermissionStatus.granted) {
    final cardDetails = await CardScanner.scanCard();
    if (cardDetails != null) {
      print(cardDetails.toString());
      print(cardDetails.cardNumber);
      cardNumberController.text = cardDetails.cardNumber.toCardNumber();
      cardExpirationDateController.text = cardDetails.expiryDate;
    }
  }
}

Future<PermissionStatus> _getCameraPermission() async {
  if (await Permission.camera.request().isGranted) {
    return PermissionStatus.granted;
  } else {
    return PermissionStatus.denied;
  }
}

extension on String {
  String toCardNumber() {
    String number = '';
    int c = 0;
    for (int i = 0; i < this.length; i++) {
      if (this.codeUnitAt(i) >= 47 && this.codeUnitAt(i) <= 57) {
        c++;
        number += this[i];
        if (c % 4 == 0) number += ' ';
      }
    }
    return number.trim();
  }
}
