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

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

  ngOnInit() {
    this.curAllQues = {}
    this.selectedObj = {}
    this.setOptionSelected()
  }
  getAnswer(question, options) {
    const questionId = question['questionId']
    console.log('select', this.selectedObj, options)
    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]] }
    })
    const ret = {
      pageId: 9,
      questions
    }
    this.getAllAnswer.emit(ret)
  }
  setOptionSelected() {
    const questions = this.curPageData['questions']
    if (!questions) {
      return
    }
    questions.map(question => {
      question['options'].forEach(option => {
        if (option['selected']) {
          this.selectedObj[question['questionId']] = option
        }
      })
    })
  }
}
