import { Pipe, PipeTransform, ChangeDetectorRef, OnDestroy, Injectable } from '@angular/core';
import { VATType } from '@swagger/oms';
import { VatService } from '../../../core/services/vat.service';
import { take, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';

@Pipe({
  name: 'vatType',
  pure: false,
})
export class VatTypePipe implements PipeTransform, OnDestroy {
  onDestroy$ = new Subject();

  value: VATType;
  result: string;

  constructor(private vatService: VatService, private cdr: ChangeDetectorRef) {}

  transform(value: VATType): string {
    if (this.value !== value) {
      this.value = value;
      this.vatService
        .getVats()
        .pipe(takeUntil(this.onDestroy$), take(1))
        .subscribe((vats) => {
          const vat = vats.find((f) => f.vatType === value);
          if (vat) {
            this.result = `${vat.value}%`;
            this.cdr.markForCheck();
          }
        });
    }

    return this.result;
  }

  ngOnDestroy() {
    this.onDestroy$.next();
    this.onDestroy$.complete();
    delete this.onDestroy$;
  }
}
