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

@Injectable()
export class ArticleSearchMainAutocompleteProvider extends UiFilterAutocompleteProvider {
  for = 'catalog';

  constructor(private domainCatalogSearch: DomainCatalogService) {
    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 > 2) {
      return this.domainCatalogSearch
        .searchComplete({
          queryToken: {
            filter,
            input: input.value,
            catalogType: undefined,
            take: 5,
            type,
          },
        })
        .pipe(
          catchError(() => of({ result: [] })),
          map((res) => res.result)
        );
    }

    return of([]);
  }
}
