import 'package:get/get.dart';

import '../services/currency_service.dart';

String formatCount(num n) {
  final v = n.toDouble();
  if (v >= 1000000000) return '${_trimZero(v / 1000000000)}B';
  if (v >= 1000000) return '${_trimZero(v / 1000000)}M';
  if (v >= 1000) return '${_trimZero(v / 1000)}K';
  return _trimZero(v);
}

String formatCurrency(num? amount, {bool applyConversion = false}) {
  final a = (amount ?? 0).toDouble();

  if (Get.isRegistered<CurrencyService>()) {
    try {
      final svc = Get.find<CurrencyService>();
      return svc.format(a, applyConversion: applyConversion);
    } catch (_) {}
  }

  final fixed = a.toStringAsFixed(2);
  final parts = fixed.split('.');
  final intPart = parts[0];
  final decPart = parts[1];

  final withThousands = _withThousands(intPart, ',');
  return '\$$withThousands.$decPart';
}

String _trimZero(num v) {
  final s = v.toStringAsFixed(1);
  if (s.endsWith('.0')) return s.substring(0, s.length - 2);
  return s;
}

String _withThousands(String digits, String sep) {
  final buf = StringBuffer();
  int count = 0;
  for (int i = digits.length - 1; i >= 0; i--) {
    buf.write(digits[i]);
    count++;
    if (count == 3 && i != 0) {
      buf.write(sep);
      count = 0;
    }
  }
  return buf.toString().split('').reversed.join();
}

String formatPrice(num n) {
  final v = n.toDouble();
  if (v >= 1000000000) return '${_trimZero(v / 1000000000)}B';
  if (v >= 1000000) return '${_trimZero(v / 1000000)}M';
  if (v >= 1000) return '${_trimZero(v / 1000)}K';
  return _trimZero(v);
}

String formatCurrencyCompact(double amount, {bool applyConversion = false}) {
  final cs = Get.isRegistered<CurrencyService>()
      ? Get.find<CurrencyService>().current
      : null;

  double num = amount;
  if (applyConversion && cs != null) {
    num = amount * cs.conversionRate;
  }

  final short = formatCount(num);

  if (cs == null) return short;

  return cs.position == '1' ? '${cs.symbol}$short' : '$short${cs.symbol}';
}
