import { Component, OnInit, ChangeDetectionStrategy, Input, EventEmitter, Output, ElementRef, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'group-list',
  templateUrl: './group-list.component.html',
  styleUrls: ['./group-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class GroupListComponent implements OnInit {
  getArr(){return this.form.get('arr') as FormArray}
  @ViewChild('input') input: ElementRef;
  @Output() addGroup = new EventEmitter()
  @Output() removeGroup = new EventEmitter()
  @Input() form: FormGroup;
  @Input() index;
  @Input() category;
  @Input() first;
  @Input() wholeForm;
  data;
  totalQuestion;
  table;
  column = ['3','4','5','6']
  constructor(
    public fb: FormBuilder,
    private swSV: SweetalertService
  ) { }

  ngOnInit(): void {
    if(!environment.hideForm) console.log('ข้อมูลแบบชุด : ',this.category)
  }

  add(){
    this.addGroup.emit()
  }

  remove(){
    this.removeGroup.emit(this.index)
  }

  isMoreThan360(event){
    if(event.target.valueAsNumber > 360) return this.form.get('exam_time').setValue(360)
  }

  onChange(x){
    const form = this.wholeForm.getRawValue()
    const duplicateData = form.random_question_details.find(a => a.question_set_uid == x.question_category_uid)
    if(duplicateData){
      this.swSV.errText('มีข้อมูลซ้ำ')
      this.remove()
    } else {
      const auttanai = x.question_category_list_child.reduce((acc,cur) => {return acc+cur.total_question_auttanai},0)
      const porranai = x.question_category_list_child.reduce((acc,cur) => {return acc+cur.total_question_porranai},0)
      const easy = x.question_category_list_child.reduce((acc,cur) => {return acc + cur.total_question_easy},0)
      const medium = x.question_category_list_child.reduce((acc,cur) => {return acc + cur.total_question_medium},0)
      const hard = x.question_category_list_child.reduce((acc,cur) => {return acc + cur.total_question_hard},0)
      const total_question = x.question_category_list_child.reduce((acc,cur) => {return acc + cur.total_question},0)
      this.form.get('total_question_easy').setValue(easy)
      this.form.get('total_question_medium').setValue(medium)
      this.form.get('total_question_hard').setValue(hard)
      this.form.get('total_question_porranai').setValue(porranai)
      this.form.get('total_question_auttanai').setValue(auttanai)
      this.form.get('total_question').setValue(total_question)
      this.form.get('question_set_uid').setValue(x.question_category_uid)
    }
  }

}


