import { Injectable } from '@angular/core';
import { DomainGoodsService } from '@domain/oms';
import { UiFilterAutocomplete, UiFilterAutocompleteProvider, UiInput } from '@ui/filter';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable()
export class GoodsOutSearchMainAutocompleteProvider extends UiFilterAutocompleteProvider {
  for = 'goods-out';

  constructor(private domainGoodsInService: DomainGoodsService) {
    super();
  }

  complete(input: UiInput): Observable<UiFilterAutocomplete[]> {
    const token = input?.parent?.parent?.getQueryToken();
    const filter = token?.filter;
    const type = Object.keys(token?.input).join(';');

    if (input.value.length >= 3) {
      return this.domainGoodsInService
        .warenausgabeComplete({
          filter,
          input: input.value,
          take: 5,
          type,
        })
        .pipe(
          catchError(() => of({ result: [] })),
          map((res) => res.result)
        );
    } else {
      return of([]);
    }
  }
}
