import {Component, Input, OnDestroy, OnInit} from '@angular/core';
import {ApiService} from "../../services/api.service";
import {combineLatest, Subject} from "rxjs";
import {Participant} from "../../../types/participant";
import {VersusItem} from "../../../types/versus-item";
import {VoiceService} from "../../services/voice.service";
import {getAudioPath} from "../../helper/tts.helper";
import {takeUntil} from "rxjs/operators";

@Component({
  selector: 'app-versus',
  templateUrl: './versus.component.html',
  styleUrls: ['./versus.component.scss']
})
export class VersusComponent implements OnInit, OnDestroy{
  @Input() player1: number;
  @Input() player2: number;
  player1data: Participant;
  player2data: Participant;
  destroyed$ = new Subject<void>();
  playersLoaded = false;
  versusData: VersusItem | null = null;

  constructor(private apiService: ApiService, private voiceService: VoiceService) {
  }
  ngOnInit() {
    this.loadPlayersData();
    this.loadTask();
    this.playAudio();
  }
  ngOnDestroy() {
    this.destroyed$.complete();
  }

  playAudio() {
    this.voiceService.playAudio(getAudioPath('Схватка!'));
  }

  loadPlayersData() {
    const player1Data$ = this.apiService.getParticipant(this.player1);
    const player2Data$ = this.apiService.getParticipant(this.player2);
    combineLatest([player1Data$,player2Data$]).pipe(takeUntil(this.destroyed$)).subscribe(([d1,d2]) => {
      this.player1data = d1;
      this.player2data = d2;
      this.playersLoaded = true;
    })
  }

  private loadTask() {
    setTimeout(() => {
      this.apiService.getVersus().pipe(takeUntil(this.destroyed$)).subscribe((r) => {
        this.versusData = r;
      })
    }, 1500);

  }
}
