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

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

  ngOnInit() {
    this.selectedObj = {}
    this.setOptionSelected()
  }
  getAnswer(option) {
    if (!this.selectedObj['selected']) {
      this.selectedObj = option
      option['selected'] = true
    } else {
      if (this.selectedObj['optionId'] != option.optionId) {
        this.selectedObj['selected'] = false
        option['selected'] = true
        this.selectedObj = option
      }
    }
    const ret = {
      pageId: this.curPageData['pageId'],
      questions: [
        {
          questionId: this.curPageData['questions'][0].questionId,
          options: [option]
        }
      ]
    }
    this.getAllAnswer.emit(ret)
  }

  setOptionSelected() {
    const options = this.curPageData['questions'][0].options
    if (!options) {
      return
    }
    options.forEach(option => {
      if (option['selected']) {
        this.selectedObj = option;
        const ret = {
          pageId: this.curPageData['pageId'],
          questions: [
            {
              questionId: this.curPageData['questions'][0].questionId,
              options: [this.selectedObj]
            }
          ]
        }
        this.getAllAnswer.emit(ret);
      }
    })
  }
}
