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

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

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

  @Input() ictFormat: number;
  @Output() ictFormatChange: EventEmitter<string> = new EventEmitter<string>();
  @Input() arg: string;

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

  ngOnChanges(changes: SimpleChanges): void {
  //  console.log("===arg===", this.arg);
    this.format(this.ictFormat);
  }

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

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