import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { ApiService } from "../../services/api.service";
import { takeUntil } from "rxjs/operators";
import { Subject, Subscription } from "rxjs";
import { Question } from "../../../types/question";
import { EventService } from "../../services/event.service";
import { VoiceService } from "../../services/voice.service";

@Component({
  selector: 'app-question',
  templateUrl: './question.component.html',
  styleUrls: ['./question.component.scss']
})
export class QuestionComponent implements OnInit, OnDestroy  {
  @Input() question: Question;
  destroyed$ = new Subject<void>();
  private questionSubscription: Subscription;
  countdownInterval:ReturnType<typeof setInterval>|null= null;
  countdown = 0;
  readonly countDownTimer = 20;


  constructor(private apiService:ApiService, private eventService: EventService, private voiceService: VoiceService) { }
  ngOnInit(): void {
    if(this.question) {
      this.voiceService.playAudio(this.voiceService.getAudioUrl(this.question.text));
      return;
    }
    setTimeout(() => this.getQuestion(), 3000);

    this.eventService.gameQueueEvent.pipe(takeUntil(this.destroyed$)).subscribe(() => {
      this.countdown = -1;
    });

    this.startCountdown();

    this.questionSubscription = this.eventService.questionChangedEvent.subscribe(() =>{
      this.getQuestion();
      this.countdown = 20;
    });
    this.setUpVersusHandler();
  }
  startCountdown() {
    this.countdown = this.countDownTimer;
    this.countdownInterval = setInterval(() => {
      if(this.countdown === 0) {
        this.continueGame();
      }
      this.countdown--;
    }, 1000)
  }

  setUpVersusHandler() {
    this.eventService.versusBegin.pipe(takeUntil(this.destroyed$)).subscribe((r) => {
      if(this.countdownInterval) {
        clearInterval(this.countdownInterval);
      }
    });
    this.eventService.versusBegin.pipe(takeUntil(this.destroyed$)).subscribe((r) => {
      this.startCountdown();
    })
  }

  continueGame() {
      this.apiService.continueGame().subscribe((r) => {
        console.log(r);
      });
  }

  getQuestion() {
    this.apiService.getQuestion().pipe(
        takeUntil(this.destroyed$)
    ).subscribe(r => {
      if (this.question && this.question.text === r.text) {
        return;
      }
      this.question = r;
      this.voiceService.playAudio(this.voiceService.getAudioUrl(r.text));
    });
  }

  ngOnDestroy() {
    if (this.questionSubscription) {
      this.questionSubscription.unsubscribe();
    }
    this.destroyed$.next();
    this.destroyed$.complete();
  }

}
