import { Injectable } from '@angular/core';
import { PaginationParams } from '@msfa-models/api/params.model';
import { BehaviorSubject, combineLatest } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { DeltagareHandelserApiService } from './api/deltagare-handelser-api.service';

const DEFAULT_PARAMS: PaginationParams = {
  page: 1,
  limit: 10,
};

@Injectable({
  providedIn: 'root',
})
export class DeltagareHandelserService {
  private _params$ = new BehaviorSubject<PaginationParams>(DEFAULT_PARAMS);
  private _genomforandeReferens$ = new BehaviorSubject<number>(null);

  deltagareHandelserData$ = combineLatest([this._genomforandeReferens$, this._params$]).pipe(
    switchMap(([genomforandeReferens, params]) => {
      return this.deltagareHandelserApiService.fetchDeltagareHandelser$(genomforandeReferens, params);
    })
  );

  constructor(private deltagareHandelserApiService: DeltagareHandelserApiService) {}

  public setPage(page: number): void {
    this._params$.next({ ...this._params$.getValue(), page });
  }

  public setGenomforandeReferens$(genomforandeReferens: number): void {
    this._genomforandeReferens$.next(genomforandeReferens);
  }

  public resetParams(): void {
    this._params$.next(DEFAULT_PARAMS);
  }
}
