import { Answer } from './../../../test_model';
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-gaps',
  templateUrl: './gaps.component.html',
  styleUrls: ['./gaps.component.css']
})
export class GapsComponent implements OnInit, OnDestroy {
  private _question;
  @Output() emitNextQuestionRequest = new EventEmitter();
  private id;
  private verifyAnswerSubscription: ISubscription;
  interval: any;
  public timeLeft = 0;
  @ViewChild('f') public form: NgForm;

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

  nextQuestion(f) {
    this.id = this.route.snapshot.params.id;
    const answers = this.question.answers.filter(element => {
      return element.is_gap;
    });
    const gapsContent = [];
    answers.forEach(element => {
      gapsContent.push({ id: element.id, content: f.value[element.id] });
    });
    const body = { id: this.question.id, type: 'gaps', answers: gapsContent };
    this.verifyAnswerSubscription = this.testsService.verifyAnswer(this.id, body).subscribe(d => {
      $('.answers').find('[type="text"]').prop('value', '');
      this.emitNextQuestionRequest.emit(d);
    });
  }

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

}
