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

@Pipe({
  name: 'productGroup',
  pure: false,
})
export class ProductGroupPipe implements PipeTransform, OnDestroy {
  result: string;

  productGroup$ = new Subject<string>();

  productGroupSubscription = this.productGroup$
    .pipe(
      distinctUntilChanged(),
      switchMap((productGroup) =>
        this._domainRemission
          .getProductGroups()
          .pipe(map((productGroups) => productGroups.find((productGroupItem) => productGroupItem.key === productGroup)))
      )
    )
    .subscribe((productGroup) => {
      this.result = productGroup?.value;
      this._cdr.markForCheck();
    });

  constructor(private readonly _domainRemission: DomainRemissionService, private _cdr: ChangeDetectorRef) {}

  ngOnDestroy(): void {
    this.productGroupSubscription.unsubscribe();
  }

  transform(value: string): any {
    this.productGroup$.next(value);

    return this.result;
  }
}
