import { Injectable } from '@angular/core';
import { Activity } from '@msfa-models/activity.model';
import { DeltagareAvrop } from '@msfa-models/avrop.model';
import { mapResponseToPeriodiskRedovisning, PeriodiskRedovisning } from '@msfa-models/periodisk-redovisning.model';
import { DeltagareApiService } from '@msfa-services/api/deltagare.api.service';
import { GemensamPlaneringApiService } from '@msfa-services/api/gemensam-planering-api.service';
import { PeriodiskRedovisningApiService } from '@msfa-services/api/periodisk-redovisning.api.service';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';

@Injectable()
export class PeriodiskRedovisningViewService {
  private _activities$: Observable<Activity[]> = this.gemensamPlaneringApiService.fetchActivities$();

  constructor(
    private periodiskRedovisningApiService: PeriodiskRedovisningApiService,
    private gemensamPlaneringApiService: GemensamPlaneringApiService,
    private deltagareApiService: DeltagareApiService
  ) {}

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

  public fetchPeriodiskRedovisning$(handlingId: string): Observable<PeriodiskRedovisning> {
    return this._activities$.pipe(
      switchMap(activities =>
        this.periodiskRedovisningApiService
          .fetchPeriodiskRedovisning$(handlingId)
          .pipe(map(({ data }) => mapResponseToPeriodiskRedovisning(data, activities)))
      )
    );
  }
}
