import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { UnsubscribeDirective } from '@msfa-directives/unsubscribe.directive';
import { environment } from '@msfa-environment';
import { TjanstResponse } from '@msfa-models/api/tjanst.response.model';
import { mapResponseToTjanst, Tjanst } from '@msfa-models/tjanst.model';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter, map, switchMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class TjanstService extends UnsubscribeDirective {
  private _apiBaseUrl = `${environment.api.url}/tjanster`;
  private _tjanster$ = new BehaviorSubject<Tjanst[]>(null);

  public tjanster$: Observable<Tjanst[]> = this._tjanster$.asObservable();

  private _fetchTjanster$: Observable<Tjanst[]> = this.tjanster$.pipe(
    filter(tjanster => !tjanster?.length),
    switchMap(() =>
      this.httpClient
        .get<{ data: TjanstResponse[] }>(this._apiBaseUrl)
        .pipe(map(({ data }) => data.map(tjanst => mapResponseToTjanst(tjanst))))
    )
  );

  constructor(private httpClient: HttpClient) {
    super();
    super.unsubscribeOnDestroy(
      this._fetchTjanster$.subscribe(tjanster => {
        this._tjanster$.next(tjanster);
      })
    );
  }
}
