import 'package:intl/intl.dart';

class ParserHelper {
  //todo : convert to extension
  static int parseInt(String value) {
    int result;
    try {
      result = int.parse(value);
    } catch (err) {
      result = 0;
    }
    return result;
  }

  static double parseDouble(String value) {
    double result;
    try {
      result = double.parse(value);
    } catch (err) {
      result = 0.0;
    }
    return result;
  }

  static String roundNumber(dynamic value) {
    String valueToString = value.toString();
    num number = num.tryParse(valueToString.isNotEmpty
            ? valueToString.contains(',')
                ? valueToString.replaceAll(',', '')
                : valueToString
            : '0') ??
        0;
    int roundedNum = number.round();

    return NumberFormat("#,###,###", 'en_US').format(roundedNum);
  }

  static String roundArea(dynamic value) {
    if (value.accessTokenIsNotEmpty && value.contains(' ')) {
      List<String> split = value!.split(' ');
      String formattedArea = ParserHelper.roundNumber(split[0]);

      return '$formattedArea ${split[1]}';
    } else {
      String valueToString = value.toString();
      num number = num.tryParse(valueToString.isNotEmpty
              ? valueToString.contains(',')
                  ? valueToString.replaceAll(',', '')
                  : valueToString
              : '0') ??
          0;
      int roundedNum = number.round();

      return NumberFormat("#,###,###", 'en_US').format(roundedNum);
    }
  }

  static String oneDecimal(num value) {
    String numWithOneDecimal = value.toStringAsFixed(1);
    if (numWithOneDecimal.contains('.')) {
      List<String> numList = [];
      numList = numWithOneDecimal.split('.');
      // Example: if the number is 12.0 change it to 12
      if (numList[1] == '0') {
        numWithOneDecimal = numList[0];
      }
    }
    return numWithOneDecimal;
  }
}
