import { ChangeDetectorRef, OnDestroy, Pipe, PipeTransform } from '@angular/core';
import { DomainRemissionService } from '@domain/remission';
import { combineLatest, Subject } from 'rxjs';
import { map } from 'rxjs/operators';

@Pipe({
  name: 'supplier',
  pure: false,
})
export class SupplierPipe implements PipeTransform, OnDestroy {
  result: string;
  supplierId$ = new Subject<number>();

  supplierIdSubscription = combineLatest([this._remissionService.getSuppliers(), this.supplierId$])
    .pipe(map(([suppliers, supplierId]) => suppliers?.find((supplier) => supplier.id === supplierId)?.name))
    .subscribe((result) => {
      this.result = result;
      this._cdr.markForCheck();
    });

  constructor(private _remissionService: DomainRemissionService, private _cdr: ChangeDetectorRef) {}
  ngOnDestroy(): void {
    this.supplierIdSubscription.unsubscribe();
  }

  transform(supplierId: number): string {
    this.supplierId$.next(supplierId);

    return this.result;
  }
}
