import { Injectable } from '@angular/core';
import { DeltagareAvrop } from '@msfa-models/avrop.model';
import { FranvaroReason } from '@msfa-models/franvaro-reason.model';
import { FranvaroReport, mapResponseToFranvaro } from '@msfa-models/franvaro.model';
import { DeltagareApiService } from '@msfa-services/api/deltagare.api.service';
import { FranvaroReportApiService } from '@msfa-services/api/franvaro-report.api.service';
import { HandlingarApiService } from '@msfa-services/api/handlingar.api.service';
import { combineLatest, Observable } from 'rxjs';
import { filter, map, switchMap } from 'rxjs/operators';

@Injectable()
export class FranvaroReportViewService {
  private _franvaroReasons$: Observable<FranvaroReason[]> = this.franvaroReportApiService.fetchReasons$();
  private _otherFranvaroReasons$: Observable<
    FranvaroReason[]
  > = this.franvaroReportApiService.fetchOtherKnownReasons$();

  constructor(
    private handlingarApiService: HandlingarApiService,
    private franvaroReportApiService: FranvaroReportApiService,
    private deltagareApiService: DeltagareApiService
  ) {}

  public fetchAvropInformation$(genomforandeReferens: number): Observable<DeltagareAvrop> {
    return this.deltagareApiService.fetchAvropInformation$(genomforandeReferens);
  }

  public fetchFranvaroReport$(handlingId: string): Observable<FranvaroReport> {
    return combineLatest([this._franvaroReasons$, this._otherFranvaroReasons$]).pipe(
      filter(([reasons, otherReasons]) => !!(reasons && otherReasons)),
      switchMap(([reasons, otherReasons]) => {
        return this.handlingarApiService.fetchFranvaroReport$(handlingId).pipe(
          map(({ data }) => ({
            genomforandeReferens: data.genomforandeReferens,
            franvaro: mapResponseToFranvaro(data.franvaro, reasons, otherReasons),
          }))
        );
      })
    );
  }
}
