interface NumberFormatModel {
  value: string | number,

  unitsLabel: string,
  thousandsLabel: string,
  millionsLabel: string,
  billionsLabel: string,

  decimalDelimiter: string,
  decimalLength: number
}

export class FormatterUtils {

  public static formatNumber(model: NumberFormatModel) {
    let numberValue = Number(model.value);
    let abs = Math.abs(numberValue);

    let unitsLabel: string;

    if (abs < 1_000) {
      unitsLabel = model.unitsLabel;
    }
    else if (abs < 1_000_000) {
      numberValue /= 1_000;
      unitsLabel = model.thousandsLabel;
    }
    else if (abs < 1_000_000_000) {
      numberValue /= 1_000_000;
      unitsLabel = model.millionsLabel;
    }
    else {
      numberValue /= 1_000_000_000;
      unitsLabel = model.billionsLabel;
    }

    let formattedNumber = FormatterUtils.prepareValue(numberValue, model.decimalDelimiter, model.decimalLength)
    return {
      formattedNumber: formattedNumber,
      label: unitsLabel
    };
  }

  private static prepareValue(value: number, decimalDelimiter: string, decimalLength: number) {
    if (!decimalDelimiter) {
      return value.toFixed(0);
    }

    let formattedValue = value.toFixed(decimalLength)
        .replace('.', decimalDelimiter);

    while (formattedValue.charAt(formattedValue.length - 1) == '0') {
      formattedValue = formattedValue.substring(0, formattedValue.length - 1);
    }

    if (formattedValue.charAt(formattedValue.length - 1) == decimalDelimiter) {
      formattedValue = formattedValue.replace(decimalDelimiter, '');
    }

    return formattedValue;
  }

}