import { Injectable } from '@angular/core';
import { DeltagareAvrop } from '@msfa-models/avrop.model';
import { AvvikelseQuestion } from '@msfa-models/avvikelse-question.model';
import { AvvikelseReason } from '@msfa-models/avvikelse-reason.model';
import { AvvikelseReport, mapResponseToAvvikelse } from '@msfa-models/avvikelse.model';
import { AvvikelseApiService } from '@msfa-services/api/avvikelse-api.service';
import { DeltagareApiService } from '@msfa-services/api/deltagare.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 AvvikelseReportViewService {
  private _avvikelseReasons$: Observable<AvvikelseReason[]> = this.avvikelseApiService.fetchAvvikelseReasons$();
  private _avvikelseQuestions$: Observable<AvvikelseQuestion[]> = this.avvikelseApiService.fetchAvvikelseQuestions$();

  constructor(
    private handlingarApiService: HandlingarApiService,
    private deltagareApiService: DeltagareApiService,
    private avvikelseApiService: AvvikelseApiService
  ) {}

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

  public fetchAvvikelseReport$(handlingId: string): Observable<AvvikelseReport> {
    return combineLatest([this._avvikelseReasons$, this._avvikelseQuestions$]).pipe(
      filter(([reasons, questions]) => !!(reasons && questions)),
      switchMap(([reasons, questions]) => {
        return this.handlingarApiService.fetchAvvikelseReport$(handlingId).pipe(
          map(({ data }) => ({
            genomforandeReferens: data.genomforandeReferens,
            avvikelse: mapResponseToAvvikelse(data.avvikelseAlternativ, reasons, questions),
          }))
        );
      })
    );
  }
}
