import { ChangeDetectionStrategy, Component, OnDestroy } from '@angular/core';
import { Avrop, AvropAndMeta } from '@msfa-models/avrop.model';
import { Handledare } from '@msfa-models/handledare.model';
import { AvropService } from '@msfa-services/avrop.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'msfa-avrop',
  templateUrl: './avrop.component.html',
  styleUrls: ['./avrop.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AvropComponent implements OnDestroy {
  readonly totalAmountOfSteps = 3;
  currentStep$: Observable<number> = this.avropService.currentStep$;
  error$: Observable<string> = this.avropService.error$;
  avropData$: Observable<AvropAndMeta> = this.avropService.avropData$;
  selectedAvrop$: Observable<Avrop[]> = this.avropService.selectedAvrop$;
  availableHandledare$: Observable<Handledare[]> = this.avropService.availableHandledare$;
  selectedHandledare$: Observable<Handledare | null> = this.avropService.selectedHandledare$;
  avropIsLocked$: Observable<boolean> = this.avropService.avropIsLocked$;
  handledareConfirmed$: Observable<boolean> = this.avropService.handledareIsConfirmed$;
  avropIsSubmitted$: Observable<boolean> = this.avropService.avropIsSubmitted$;
  avropLoading$: Observable<boolean> = this.avropService.avropLoading$;
  showUnauthorizedError$: Observable<boolean> = this.avropService.showUnauthorizedError$;

  constructor(private avropService: AvropService) {}

  ngOnDestroy(): void {
    this.returnToStep1();
  }

  updateSelectedAvrop(deltagareList: Avrop[], currentStep: number): void {
    if (currentStep !== 1 && !deltagareList.length) {
      this.avropService.goToStep1();
    } else {
      this.avropService.setSelectedAvrop(deltagareList);
    }
  }

  lockSelectedAvrop(): void {
    this.avropService.lockSelectedAvrop();
  }

  unlockSelectedAvrop(): void {
    this.avropService.unlockSelectedAvrop();
  }

  confirmHandledare(): void {
    this.avropService.confirmHandledare();
  }

  unconfirmHandledare(): void {
    this.avropService.unconfirmHandledare();
  }

  async save(): Promise<void> {
    return this.avropService.save();
  }

  changeHandledare(handledareId: string): void {
    this.avropService.assignHandledare(handledareId);
  }

  returnToStep1(): void {
    this.avropService.goToStep1();
  }

  resetError(): void {
    this.avropService.resetError();
  }

  setNewPage(page: number): void {
    this.avropService.setPage(page);
  }
}
