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

@Component({
  selector: 'app-pairs',
  templateUrl: './pairs.component.html',
  styleUrls: ['./pairs.component.css']
})
export class PairsComponent implements OnInit, OnChanges, OnDestroy {
  private _question;
  @Output() emitNextQuestionRequest = new EventEmitter();
  private id;
  private verifyAnswerSubscription: ISubscription;
  leftSides = [];
  rightSides = [];
  leftSidesToSend = [];
  selectedLeftSide = { indexOfLeftSide: Number, leftSideText: String, from: '' };
  interval: any;
  public timeLeft = 0;

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

  nextQuestion(f = null) {
    this.id = this.route.snapshot.params.id;
    const answers = [];
    this.leftSidesToSend.forEach((element, index) => {
      answers.push({
        left: element,
        right: this.rightSides[index]
      });
    });
    const body = {
      id: this.question.id, type: 'pairs',
      answers: answers
    };
    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();
      }
    }, 1000);
  }

  leftSideClick(item, i) {
    if (item !== '' && item !== undefined) {
      if (this.selectedLeftSide.from === 'leftSides') {
        this.selectedLeftSide = { indexOfLeftSide: undefined, leftSideText: undefined, from: undefined };
      } else {
        this.selectedLeftSide = { indexOfLeftSide: i, leftSideText: item, from: 'leftSides' };
      }
    }
  }

  leftSideToSendClick(item, i) {
    if (this.selectedLeftSide.from === 'leftSides') {
      const helper = this.leftSidesToSend[i];
      this.leftSidesToSend[i] = this.selectedLeftSide.leftSideText;
      this.leftSides[Number(this.selectedLeftSide.indexOfLeftSide)] = helper;
      this.selectedLeftSide = { indexOfLeftSide: undefined, leftSideText: undefined, from: undefined };
    } else if (this.selectedLeftSide.from === 'leftSidesToSend') {
      const helper = this.leftSidesToSend[i];
      this.leftSidesToSend[i] = this.selectedLeftSide.leftSideText;
      this.leftSidesToSend[Number(this.selectedLeftSide.indexOfLeftSide)] = helper;
      this.selectedLeftSide = { indexOfLeftSide: undefined, leftSideText: undefined, from: undefined };
    } else if (item !== '' && item !== undefined) {
      this.selectedLeftSide = { indexOfLeftSide: i, leftSideText: item, from: 'leftSidesToSend' };
    }
  }

  prepareLists() {
    this.selectedLeftSide = { indexOfLeftSide: undefined, leftSideText: undefined, from: undefined };
    this.leftSides = [];
    this.rightSides = [];
    this.leftSidesToSend = [];
    this.leftSides = JSON.parse(JSON.stringify(this.question.answers[0].left));
    this.rightSides = JSON.parse(JSON.stringify(this.question.answers[0].right));
    this.leftSides.forEach(element => {
      this.leftSidesToSend.push('');
    });
  }

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

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

  ngOnInit() {}

  ngOnChanges() {
    this.prepareLists();
  }

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