import {Component, OnInit} from '@angular/core';
import {ApiService, EndgameResultsDto, FeatureFlagStateDto} from "../../services/api.service";
import {
  Subject,
  firstValueFrom,
  combineLatest,
  merge
} from "rxjs";
import { takeUntil} from "rxjs/operators";
import {VoiceService} from "../../services/voice.service";
import {animate, style, transition, trigger} from "@angular/animations";
import {Participant} from "../../../types/participant";
import {SharedMethods} from "../../shared/sharedmethods";

@Component({
  selector: 'app-endgamepoints',
  templateUrl: './endgamepoints.component.html',
  styleUrls: ['./endgamepoints.component.scss'],
  animations: [
    trigger('slideOut', [
      transition(':leave', [
        animate(
          '1300ms ease-in',
          style({ transform: 'translateY(-100%)', opacity: 0 })
        ),
      ]),
    ])]
})
export class EndgamepointsComponent implements OnInit{
  loaded = false;
  useCssAnimation = false;
  destroyed$ = new Subject();
  showInitialText = true;
  showMaxAmountOfInvalidAnswers = false;
  endgameResults: EndgameResultsDto | null;
  participants: Participant[] = [];
  maxAmountOfPenalties = false;
  maxAmountOfRewards = false;
  constructor(private apiService: ApiService, private  voiceService: VoiceService) {
  }


  ngOnInit(): void {
    const ff$ = this.apiService.getFeatureFlagState("EndgamePointsUseCssAnimation");
    // @ts-ignore
    const results$ = this.apiService.getEndgameResults();
    combineLatest([results$, ff$])
      .pipe(takeUntil(this.destroyed$))
      .subscribe(([results,ff]) => {
        const userData$ = [];
        userData$.push(
          this.apiService.getParticipant(results.maxInvalidAnswers.id),
          this.apiService.getParticipant(results.maxPenalties.id),
          this.apiService.getParticipant(results.maxRewards.id),
          );
        merge(...userData$).pipe(takeUntil(this.destroyed$)).subscribe((r) => this.participants.push(r));
        this.useCssAnimation = ff.state;
        this.endgameResults = results;
        this.loaded = true;
        this.playScene().then(() => {});
        console.log(results);
    });
  }


  async playScene() {
    await firstValueFrom(this.voiceService.playAudio$(this.voiceService.getAudioUrl("Время наградить особо отличившихся!")));
    this.showInitialText = false;
    await SharedMethods.sleep(1000);
    this.showMaxAmountOfInvalidAnswers = true;
    await SharedMethods.sleep(500);
    await firstValueFrom(this.voiceService.playAudio$(this.voiceService.getAudioUrl(` За максимальное количество неверных ответов, плюс два очка получает ${this.endgameResults?.maxInvalidAnswers.name}`)));
    this.showMaxAmountOfInvalidAnswers = false;
    await SharedMethods.sleep(3000);
    this.maxAmountOfPenalties = true;
    await firstValueFrom(this.voiceService.playAudio$(this.voiceService.getAudioUrl(`За самое большое количество полученных наказаний плюс два очка получил ${this.endgameResults?.maxPenalties.name}`)));
    await SharedMethods.sleep(3000)
    this.maxAmountOfPenalties = false;
    await firstValueFrom(this.voiceService.playAudio$(this.voiceService.getAudioUrl(`И чтобы сделать игру более справедливой, есть последняя номинация`)));
    this.maxAmountOfRewards = true;
    await firstValueFrom(this.voiceService.playAudio$(this.voiceService.getAudioUrl(`${this.endgameResults?.maxRewards.name} лишается двух очков за свой невероятный ум`)));
    await SharedMethods.sleep(15000);

  }


  getParticipant(id: number | undefined): Participant|null {
    if(id) {
      const p = this.participants.find(x => x.telegramId === id);
      return p !== undefined ? p : null;
    }
    return null;
  }
}
