import { Pipe, PipeTransform } from '@angular/core';
import { ConfigService } from '@shared/config/config.service';

@Pipe({
  name: 'currencyFormatter'
})
export class CurrencyFormatterPipe implements PipeTransform {
  _locale = undefined;

  constructor(private config: ConfigService) {
    this._locale = this.config.locale;
  }

  transform(
    value: string | number,
    currencyCode: string,
    currencyDisplayMode: string,
    digitsInfo: string = '1.2-2',
    locale?: any,
    signDisplay: string = 'auto',
  ): string {
    if (!locale) {
      locale = this._locale;
    }

    if (typeof value === 'string') {
      value = parseFloat(value);
    }

    let minIntegerDigits = undefined;
    let minFractionDigits = undefined;
    let maxFractionDigits = undefined;

    if (digitsInfo) {
      let digitsInfoArray = digitsInfo.split('.');
      minIntegerDigits = digitsInfoArray[0];
      let fractionDigitsInfoArray = digitsInfoArray[1].split('-');
      minFractionDigits = fractionDigitsInfoArray[0];
      if (fractionDigitsInfoArray.length === 2) {
        maxFractionDigits = fractionDigitsInfoArray[1];
      }
    }

    if (!currencyDisplayMode) {
      currencyDisplayMode = 'code';
    }
    if (currencyDisplayMode === 'symbol-narrow') {
      currencyDisplayMode = 'narrowSymbol';
    }

    return new Intl.NumberFormat(locale, {
      style: 'currency',
      currency: currencyCode,
      currencyDisplay: currencyDisplayMode,
      minimumIntegerDigits: minIntegerDigits,
      minimumFractionDigits: minFractionDigits,
      maximumFractionDigits: maxFractionDigits,
      signDisplay,
    } as any).format(value);
  }
}
