import { Injectable } from '@angular/core';
import { DeltagareAvrop } from '@msfa-models/avrop.model';
import { ContactInformation } from '@msfa-models/contact-information.model';
import { DeltagareApiService } from '@msfa-services/api/deltagare.api.service';
import { HandledareService } from '@msfa-services/handledare.service';
import { BehaviorSubject, combineLatest, merge, Observable, of } from 'rxjs';
import { map, mapTo, shareReplay, switchMap } from 'rxjs/operators';

@Injectable()
export class DeltagareCardService {
  private _activeTab$ = new BehaviorSubject<string>('0');
  activeTab$: Observable<string> = this._activeTab$.asObservable();

  private _genomforandeReferensFromParams$ = new BehaviorSubject<string | null>(null);

  currentGenomforandeReferens$: Observable<number> = this._genomforandeReferensFromParams$.pipe(
    map(genomforandeReferens => (genomforandeReferens ? +genomforandeReferens : null))
  );
  avropNeedsUpdate$: Observable<void> = this.handledareService.lastSavedHandledare$.pipe(mapTo(undefined as void));

  contactInformation$: Observable<ContactInformation> = this.currentGenomforandeReferens$.pipe(
    switchMap(genomforandeReferens =>
      genomforandeReferens
        ? merge<ContactInformation | null>(
            of(null),
            this.deltagareApiService.fetchContactInformation$(genomforandeReferens)
          )
        : null
    ),
    shareReplay(1)
  );

  avropInformation$: Observable<DeltagareAvrop> = combineLatest([
    this.currentGenomforandeReferens$,
    this.avropNeedsUpdate$,
  ]).pipe(
    switchMap(([genomforandeReferens]) =>
      genomforandeReferens ? this.deltagareApiService.fetchAvropInformation$(genomforandeReferens) : null
    ),
    shareReplay(1)
  );

  constructor(private deltagareApiService: DeltagareApiService, private handledareService: HandledareService) {}

  setGenomforandereferens(genomforandeReferens: string): void {
    if (genomforandeReferens !== this._genomforandeReferensFromParams$.value) {
      this._genomforandeReferensFromParams$.next(genomforandeReferens);
      this.setActiveTab('0');
    }
  }

  setActiveTab(tabId: string): void {
    this._activeTab$.next(tabId);
  }
}
