import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { DeltagareAvrop } from '@msfa-models/avrop.model';
import { ContactInformation } from '@msfa-models/contact-information.model';
import { Handledare } from '@msfa-models/handledare.model';
import { Role } from '@msfa-models/role.model';
import { HandledareService } from '@msfa-services/handledare.service';
import { combineLatest, Observable } from 'rxjs';
import { distinctUntilChanged, filter, map, startWith, switchMap } from 'rxjs/operators';
import { DeltagareCardService } from '../../deltagare-card.service';

@Component({
  selector: 'msfa-deltagare-tab-personal-information',
  templateUrl: './deltagare-tab-personal-information.component.html',
  styleUrls: ['./deltagare-tab-personal-information.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeltagareTabPersonalInformationComponent {
  @Input() userRoles: Role[];
  @Input() handledarePickerVisible: boolean;

  avropInformation$: Observable<DeltagareAvrop> = this.deltagareCardService.avropInformation$;
  contactInformation$: Observable<ContactInformation> = this.deltagareCardService.contactInformation$;
  availableHandledare$: Observable<Handledare[]> = this.avropInformation$.pipe(
    distinctUntilChanged((prevAvrop, currAvrop) => prevAvrop.id === currAvrop.id),
    filter(() => !!this.handledarePickerVisible),
    switchMap(avropInformation => this.handledareService.fetchAvailableHandledare$([avropInformation.id]))
  );

  dataIsLoading$: Observable<boolean> = combineLatest([this.avropInformation$, this.contactInformation$]).pipe(
    map(([avropInformation, contactInformation]) => !(contactInformation && avropInformation)),
    startWith(true)
  );

  constructor(private deltagareCardService: DeltagareCardService, private handledareService: HandledareService) {}
}
