import { Component, OnInit, Input, Output, EventEmitter, OnDestroy, ElementRef, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { TestsService } from '../../../tests.service';
import * as $ from 'jquery';
import { ISubscription, Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-true-false',
  templateUrl: './true-false.component.html',
  styleUrls: ['./true-false.component.css']
})
export class TrueFalseComponent implements OnInit, OnDestroy {
  private _question;
  private answer;
  @Output() emitNextQuestionRequest = new EventEmitter();
  private id;
  private verifyAnswerSubscription: ISubscription;
  interval: any;
  public timeLeft = 0;
  @ViewChild('true') true: ElementRef;
  @ViewChild('false') false: ElementRef;

  constructor(private route: ActivatedRoute, private testsService: TestsService) { }

  nextQuestion() {
    this.id = this.route.snapshot.params.id;
    const answers = this.question.answers;
    answers.forEach(element => {
      element.is_good = element.content === this.answer ? true : false;
    });
    const body = { id: this.question.id, type: 'true-false', answers: answers };
    this.verifyAnswerSubscription = this.testsService.verifyAnswer(this.id, body).subscribe(d => {
      $('.btn-group').find('label').removeClass('active').end().find('[type="radio"]').prop('checked', false);
      this.answer = undefined;
      this.emitNextQuestionRequest.emit(d);
    });
  }

  startTimer() {
    this.interval = setInterval(() => {
      if (this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.nextQuestion();
      }
    }, 1000);
  }

  chooseAnswer(answer: any) {
    this.answer = answer;
  }

  public get question() {
    return this._question;
  }

  @Input('question')
  public set question(data) {
    this._question = data;
    this.ngOnDestroy();
    this.timeLeft = this.question.time;
    if (this.timeLeft > 0) {
      this.startTimer();
    }
    if (this.true) {
      this.true.nativeElement.checked = false;
    }

    if (this.false) {
      this.false.nativeElement.checked = false;
    }
  }

  ngOnInit() {}

  ngOnDestroy() {
    if (this.interval) {
      clearInterval(this.interval);
    }
    if (this.verifyAnswerSubscription) {
      this.verifyAnswerSubscription.unsubscribe();
    }
  }

}
