import 'package:flutter/services.dart';
import 'package:intl/intl.dart';

class SeparatorInputFormatter extends TextInputFormatter {
  final NumberFormat _formatter;

  SeparatorInputFormatter() : _formatter = NumberFormat('#,###');

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.text.isEmpty) {
      return newValue;
    }
    String tmpText = newValue.text;
    String cleanedText = tmpText.replaceAll(RegExp(r'\D'), '');
    int? number = int.tryParse(cleanedText);
    if (number == null) {
      return oldValue;
    }
    String formattedText = _formatter.format(number);
    int selectionIndex = formattedText.length;
    return TextEditingValue(
      text: formattedText,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
