import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'

@Component({
  selector: 'app-page8',
  templateUrl: './page8.component.html',
  styleUrls: ['./page8.component.css']
})
export class Page8Component implements OnInit {
  @Input() curPageData: Array<any>
  @Output() getAllAnswer = new EventEmitter<any>()
  curAllQues: Object

  selectedObj: Object
  questions: Array<any>;
  constructor() {}

  ngOnInit() {
    this.questions = [];
    this.curAllQues = {}
    this.selectedObj = {}
    this.setOptionSelected()
    // console.log(this.curPageData)
  }
  getAnswer(question, options) {
    const questionId = question['questionId']
    if (!this.selectedObj[questionId]) {
      this.selectedObj[questionId] = options
      options['selected'] = true
    } else {
      if (this.selectedObj[questionId].optionId != options.optionId) {
        this.selectedObj[questionId]['selected'] = false
        options['selected'] = true
        this.selectedObj[questionId] = options
      }
    }
    this.curAllQues[questionId] = options
    const questions = Object.keys(this.curAllQues).map(questionId => {
      return { questionId, options: [this.curAllQues[questionId]] }
    })
    for (let j = 0; j < this.questions.length; j++) {
      for (let i = 0; i < questions.length; i++) {
      if (questions[i]['questionId'] != this.questions[j]['questionId']) {
        questions.push(this.questions[j]);
        break;
      }
      break;
    }
  }
    const ret = {
      pageId: 8,
      questions
    }
    // console.log(this.curPageData['questions']);
    this.getAllAnswer.emit(ret)
  }
  setOptionSelected() {
    const questions2 = this.curPageData['questions']
    if (!questions2) {
      return
    }
    questions2.map(question => {
      question['options'].forEach(option => {
        if (option['selected']) {
          this.selectedObj[question['questionId']] = option
        }
      })
    })

    const questions = Object.keys(this.selectedObj).map(questionId => {
      return { questionId, options: [this.selectedObj[questionId]] }
    })
    this.questions = questions
    const ret = {
      pageId: 8,
      questions
    }
    this.getAllAnswer.emit(ret)
  }
}
