import { Injectable } from '@angular/core';
import { SearchStateSettingsLoader } from '@store/search-component-store';
import { UISettingsDTO } from '@swagger/cat';
import { CustomerService } from '@swagger/crm';
import { UiErrorModalComponent, UiModalService } from '@ui/modal';
import { memorize } from '@utils/common';
import { Observable, of } from 'rxjs';
import { catchError, map, shareReplay } from 'rxjs/operators';

@Injectable()
export class CustomerSearchStateSettingsLoader implements SearchStateSettingsLoader {
  constructor(private _customerService: CustomerService, private _modal: UiModalService) {}

  @memorize()
  load(): UISettingsDTO | Promise<UISettingsDTO> | Observable<UISettingsDTO> {
    return this._customerService.CustomerCustomerQuerySettings().pipe(
      map((res) => res.result),
      catchError((error) => {
        this._modal.open({
          content: UiErrorModalComponent,
          title: 'Fehler beim Laden des Kundenfilters',
          data: error,
        });
        return of({});
      }),
      shareReplay()
    );
  }
}
