import { Injectable } from '@angular/core';
import { SortOrder } from '@msfa-enums/sort-order.enum';
import { DeltagareParams } from '@msfa-models/api/params.model';
import { DeltagareCompact, DeltagareCompactData } from '@msfa-models/deltagare.model';
import { Sort } from '@msfa-models/sort.model';
import { BehaviorSubject, Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { DeltagareApiService } from './api/deltagare.api.service';

const DEFAULT_PARAMS: DeltagareParams = {
  page: 1,
  limit: 20,
  sort: 'fullName',
  order: SortOrder.ASC,
  onlyMyDeltagare: false,
};
@Injectable({
  providedIn: 'root',
})
export class DeltagareService {
  private _params$ = new BehaviorSubject<DeltagareParams>(DEFAULT_PARAMS);
  public sort$: Observable<Sort<keyof DeltagareCompact>> = this._params$.pipe(
    map(({ sort, order }) => ({ key: sort, order }))
  );
  public onlyMyDeltagare$: Observable<boolean> = this._params$.pipe(map(({ onlyMyDeltagare }) => onlyMyDeltagare));
  public showUnauthorizedError$: Observable<boolean> = this.deltagareApiService.showUnauthorizedError$;
  public deltagareLoading$: Observable<boolean> = this.deltagareApiService.deltagareLoading$;
  public allDeltagareData$: Observable<DeltagareCompactData> = this._params$.pipe(
    switchMap(params => this.deltagareApiService.fetchAllDeltagare$(params))
  );

  constructor(private deltagareApiService: DeltagareApiService) {}

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

  public setSort(sort: keyof DeltagareCompact): void {
    const params = this._params$.getValue();
    const order = params.sort === sort && params.order === SortOrder.ASC ? SortOrder.DESC : SortOrder.ASC;

    this._params$.next({
      ...params,
      sort,
      order,
    });
  }

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

  public setOnlyMyDeltagare(value: boolean): void {
    this._params$.next({ ...this._params$.getValue(), onlyMyDeltagare: value, page: 1 });
  }
}
