import 'package:flutter/services.dart';

class CustomTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    var re = RegExp(('[^0-9]'));
    if (newValue.selection.baseOffset == 0 && newValue.text.isNotEmpty) {
      return newValue;
    }
    if (newValue.text.isEmpty) {
      return newValue.copyWith(text: '');
    } else if (newValue.text.compareTo(oldValue.text) != 0) {
      final selectionIndexFromTheRight =
          newValue.text.length - newValue.selection.extentOffset;
      final reversedText =
      String.fromCharCodes(newValue.text.runes.toList().reversed);
      final chars = reversedText.replaceAll(re, '').split('');
      var reversedNewString = '';
      for (var i = 0; i < chars.length; i++) {
        if (i % 3 == 0 && i != 0) reversedNewString += ' ';
        reversedNewString += chars[i];
      }
      final newString =
      String.fromCharCodes(reversedNewString.runes.toList().reversed);

      return TextEditingValue(
        text: newString,
        selection: TextSelection.collapsed(
          offset: newString.length - selectionIndexFromTheRight,
        ),
      );
    } else {
      return newValue;
    }
  }
}