import { Directive, Input, Output, EventEmitter, ChangeDetectorRef, SimpleChanges } from '@angular/core';
import { DecimalPipe } from '@angular/common';

/*
    Created By    : Arun Joy
    Created On    : 20-03-2020
    Created For   : For Rate feilds decimal formatting.
*/

@Directive({
  selector: '[ictCurrency]',
  host: {
    '[value]': 'ictCurrency',
    '(change)': 'change($event.target.value)',
  }
})
export class CurrencyDirective {

  @Input() ictCurrency: number;
  @Output() ictCurrencyChange: EventEmitter<string> = new EventEmitter<string>();

  coinDec = 2;

  constructor(
    private _cdr: ChangeDetectorRef,
    private _decimalPipe: DecimalPipe
  ) { }

  ngOnChanges(changes: SimpleChanges): void {
    this.format(this.ictCurrency);
  }

  change(value) {
    this.format(value, "C");
  }

  format(value, flag?: string) {
    value = (value && value.toString()) ? (value.toString().replace(/,/gi, "")) : 0;
    let coinDec = this.coinDec;
    let pattern = "1." + coinDec + "-" + coinDec;
    value = this._decimalPipe.transform(value, pattern);
    value = value.replace(/,/gi, "");
    // this.ictCurrencyChange.next(value);
    if (!flag || flag != "C")
      this._cdr.detectChanges();
  }

}
