import {Component, OnDestroy, OnInit} from '@angular/core';
import {StudentViewService} from 'src/app/services/student-view.service';
import {StudentDataService} from 'src/app/services/student-data.service';
import {StudentInfoService} from 'src/app/services/student-info.service';
import {AnswerDao} from 'src/app/dao/answer.dao';
import {QuestionDao} from 'src/app/dao/question.dao';
import {QuestionAnswerPairDao} from '../../dao/question-answer-pair.dao';
import {MinutePaperDao} from '../../dao/minute-paper.dao';

@Component({
  selector: 'app-student-completed-view',
  templateUrl: './student-completed-view.component.html',
  styleUrls: ['./student-completed-view.component.css']
})
export class StudentCompletedViewComponent implements OnInit, OnDestroy {

  public classCode: String;
  public currentPaper: MinutePaperDao;
  public studentId: String;
  public answerList: AnswerDao[];
  public questionList: QuestionDao[];
  public questionAnswerPairs: QuestionAnswerPairDao[];

  constructor(private studentInfoService: StudentInfoService,
              private studentViewService: StudentViewService,
              private studentDataService: StudentDataService) {
  }

  ngOnInit(): void {
    this.classCode = this.studentDataService.classCode;
    this.currentPaper = this.studentDataService.currentPaper;
    this.studentId = this.studentDataService.studentId;
    this.questionList = [];
    this.answerList = [];
    this.questionAnswerPairs = [];
    this.getQuestions();
    this.getAnswers();
    this.organise();
  }

  ngOnDestroy(): void {
    this.questionList = [];
    this.answerList = [];
    this.questionAnswerPairs = [];
  }

  private organise() {
    this.questionAnswerPairs = [];
    for (let i = 0; i < this.questionList.length; i++) {
      if (this.questionList[i] && this.answerList[i]) {
        this.questionAnswerPairs.push(new QuestionAnswerPairDao(this.questionList[i], this.answerList[i]));
      }
    }
  }

  private getQuestions() {
    this.studentInfoService.getPaperQuestions(this.studentId, this.currentPaper.paperId).subscribe((data: QuestionDao[]) => {
      data.forEach(e => this.questionList.push(e));
      this.organise();
    });
  }

  private getAnswers() {
    this.studentInfoService.getStudentAnswers(this.studentId, this.currentPaper.paperId).subscribe((data: AnswerDao[]) => {
      data.forEach(e => this.answerList.push(e));
      this.organise();
    });
  }
}