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

@Component({
  selector: 'app-single-choice',
  templateUrl: './single-choice.component.html',
  styleUrls: ['./single-choice.component.css']
})
export class SingleChoiceComponent implements OnInit, OnDestroy {
  private _question;
  private answer;
  @Output() emitNextQuestionRequest = new EventEmitter();
  @Output() lifebuoy = new EventEmitter<boolean>();
  @Input() activeFifty;
  private id;
  private verifyAnswerSubscription: ISubscription;
  interval: any;
  public timeLeft = 0;
  public fifty: Boolean = false;
  @ViewChild('f') public form: NgForm;


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

  nextQuestion(f) {
    this.id = this.route.snapshot.params.id;
    let answers = [];
    if (this.fifty) {
      this.fifty = false;
      answers = this.question.answers_help;
    } else {
      answers = this.question.answers;
    }

    answers.forEach(element => {
      element.is_good = element.content === f.value.answer ? true : false;
    });

    const body = { id: this.question.id, type: 'single-choice', answers: answers };
    this.verifyAnswerSubscription = this.testsService.verifyAnswer(this.id, body).subscribe(d => {
      $('.answers').find('[type="radio"]').prop('checked', false);
      this.emitNextQuestionRequest.emit(d);
    });
  }

  fiftyFifty() {
    this.fifty = true;
    this.lifebuoy.emit(false);
  }

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

  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();
    }
  }

  ngOnInit() {}

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

}
