import 'dart:math';

class Utils {
  // static double roundToDecimalPlaces(double value, int precision) {
  //   double mod = pow(10.0, precision).toDouble();
  //   return ((value * mod).round().toDouble() / mod);
  // }

  static double roundToMultipleOfBase(double value, double base) {
      double result = value;
      double remainder = value % base;
      int precision = Utils.getFractionDigitsLength(base);

      if (remainder != 0) {
        result = Utils.addDoublesWithPrecision(result, -remainder, precision);
        if (remainder > base / 2) {
          result = Utils.addDoublesWithPrecision(result, base, precision);
        }
      }

      return result;
  }

  static double addDoublesWithPrecision(double a, double b, int precision) {
    double mod = pow(10.0, precision).toDouble();
    double difference = (a * mod) + (b * mod);
    return difference.round() / mod;
  }

  static int getFractionDigitsLength(double value) {
    final fractionDigits = value.toString().split('.');
    return fractionDigits[1] == '0' ? 0 : fractionDigits[1].length;
  }

  static String toStringMatchingTemplateFractionPrecision(
      double value, double template) {
    final precision = getFractionDigitsLength(template);
    return value.toStringAsFixed(precision);
  }

  static double convertMgPerDlToMmolPerL(int mgPerDl, {double step = 0.01}) {
    return Utils.roundToMultipleOfBase(mgPerDl * 0.0555, step);
  }

  static int convertMmolPerLToMgPerDl(double mmolPerL) {
    return (mmolPerL * 18.018).round();
  }

  static double calculateCarbs(double carbsRatio, double portionSize,
      {double step = 0.01}) {
    return Utils.roundToMultipleOfBase(carbsRatio * portionSize / 100, step);
  }

  static double calculateCarbsRatio(
      double carbsPerPortion, double portionSize, {double step = 0.01}) {
    return portionSize > 0
        ? Utils.roundToMultipleOfBase(carbsPerPortion * 100 / portionSize, step)
        : 0;
  }

  static double calculatePortionSize(
      double carbsRatio, double carbsPerPortion, {double step = 0.01}) {
    return carbsRatio > 0
        ? Utils.roundToMultipleOfBase(carbsPerPortion * 100 / carbsRatio, step)
        : 0;
  }
}
