import { Component, OnInit, ChangeDetectionStrategy, Input, Output, EventEmitter, ViewChild, ElementRef, ChangeDetectorRef } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { distinctUntilChanged, tap } from 'rxjs/operators';
import { QuestionCategoryService } from 'src/app/core/service/question/question-category.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { SweetAlertArrayOptions } from 'sweetalert2';

@Component({
  selector: 'category-list',
  templateUrl: './category-list.component.html',
  styleUrls: ['./category-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CategoryListComponent implements OnInit {
  getArr(){ return this.form.get('arr') as FormArray }
  @ViewChild('input') input: ElementRef;
  @ViewChild('porranaiEasy') multiple_choice_easy: ElementRef;
  @ViewChild('auttanaiEasy') subjective_easy: ElementRef;
  @ViewChild('porranaiMedium') multiple_choice_medium: ElementRef;
  @ViewChild('auttanaiMedium') subjective_medium: ElementRef;
  @ViewChild('porranaiHard') multiple_choice_hard: ElementRef;
  @ViewChild('auttanaiHard') subjective_hard: ElementRef;
  @Input() form: FormGroup;
  @Input() oldForm: FormGroup;
  @Input() index;
  @Input() category;
  @Input() first;
  @Input() reset;
  @Input() categoryType: any = [];
  @Output() addCategory = new EventEmitter()
  @Output() removeCategory = new EventEmitter()
  @Output() isButtonDisabled = new EventEmitter()
  data;
  test;
  isMore;
  totalQuestion;
  questionFrameData;
  column = ['1','2','3','4','5','6','7']
  constructor(
    public fb: FormBuilder,
    private swSV: SweetalertService,
    private cdr: ChangeDetectorRef,
    private questionCategorySV: QuestionCategoryService
  ) { }

  ngOnInit(): void {

  }

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

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

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

  pushQuestion(data){
    const question = data
    this.form.setControl('arr',this.fb.array(question.question_category_list_child.map((x,index) => this.createRandomQuestionDetail(x,question.question_category_master_uid,index))))
    const form = this.getArr().value
    if(form.length > 1){
      this.totalQuestion = form.reduce((acc,cur)=> {return acc + cur.total},0)
    } else {
      this.totalQuestion = form[0].total
    }
    this.isButtonDisabled.emit(this.checkCondition())
    this.test = this.getArr().value
    this.cdr.detectChanges()
  }

  onChange(event){
    this.questionCategorySV.getCategoryType(event.subject_uid,event.question_category_master_uid).pipe(
      tap(x => this.pushQuestion(x[0])),
      tap(x => this.questionFrameData = x[0]),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
  }

  createRandomQuestionDetail(x,data,index){
    return this.fb.group({
      status_id: null,
      created_by: null,
      created_datetime: null,
      updated_by: null,
      updated_datetime: null,
      deleted_by: null,
      deleted_datetime: null,
      random_question_detail_uid: null,
      random_question_uid: null,
      question_set_uid: data,
      question_sub_set_uid: x.question_category_master_uid,
      total_question_easy: [0,Validators.required],
      total_question_medium: [0,Validators.required],
      total_question_hard: [0,Validators.required],
      question_category_name_th: x.question_category_name_th,
      total: x.total_question,
      total_question: null,
      total_random: null,
      auttanai_easy: x.total_question_auttanai_easy,
      porranai_easy: x.total_question_porranai_easy,
      auttanai_medium: x.total_question_auttanai_medium,
      porranai_medium: x.total_question_porranai_medium,
      auttanai_hard: x.total_question_auttanai_hard,
      porranai_hard: x.total_question_porranai_hard,
      multiple_choice_easy: [0,Validators.required],
      subjective_easy: [0,Validators.required],
      multiple_choice_medium: [0,Validators.required],
      subjective_medium: [0,Validators.required],
      multiple_choice_hard: [0,Validators.required],
      subjective_hard: [0,Validators.required],
      row_order: index+1,
      is_ok_easy: x.is_ok_easy,
      is_ok_easy_auttanai: x.is_ok_easy_auttanai,
      is_ok_easy_porranai: x.is_ok_easy_porranai,
      is_ok_medium: x.is_ok_medium,
      is_ok_medium_auttanai: x.is_ok_medium_auttanai,
      is_ok_medium_porranai: x.is_ok_medium_porranai,
      is_ok_hard: x.is_ok_hard,
      is_ok_hard_auttanai: x.is_ok_hard_auttanai,
      is_ok_hard_porranai: x.is_ok_hard_porranai,
    })
  }

  total(input){
    if(input <= this.totalQuestion){
      this.getArr().controls.map(x => {
        x.get('total_question_easy').setValue(null)
        x.get('total_question_medium').setValue(null)
        x.get('total_question_hard').setValue(null)
      })
    } else {
      this.swSV.errText('จำนวนคำถามมากเกินกำหนด')
      this.input.nativeElement.value = 0
      this.getArr().controls.map(x => {
        x.get('total_question_easy').setValue(null)
        x.get('total_question_medium').setValue(null)
        x.get('total_question_hard').setValue(null)
      })
    }
  }

  sumTotal(index,type?){
    return this.getArr().at(index).get('subjective_easy').value +
    this.getArr().at(index).get('multiple_choice_easy').value +
    this.getArr().at(index).get('subjective_medium').value +
    this.getArr().at(index).get('multiple_choice_medium').value +
    this.getArr().at(index).get('subjective_hard').value +
    this.getArr().at(index).get('multiple_choice_hard').value
  }

  checkValidation(index,data,type,input){
    const level = type.split('_')[type.split('_').length-1]
    const isSubjective = type.split('_').includes("subjective")
    this.getArr().at(index).get('total_question').setValue(this.sumTotal(index))
    // this.test = this.getArr().value
    data.total_random = this.sumTotal(index)
    if(this.sumTotal(index) > data.total){
      this.swSV.errText('จำนวนสุ่มเกินกำหนด')
      this[type].nativeElement.value = 0
      // this.multiple_choice_hard
      this.getArr().at(index).get(type).setValue(0)
      this.getArr().at(index).get('total_question').setValue(this.sumTotal(index))
      this.getArr().at(index).get('total_random').setValue(this.sumTotal(index))
      this.test = this.getArr().value
    }else if (input > data[(isSubjective? 'auttanai_' : 'porranai_')+level]){
      this.swSV.errText('จำนวนสุ่มเกินกำหนด')
      this[type].nativeElement.value = 0
      this.getArr().at(index).get(type).setValue(0)
      this.getArr().at(index).get('total_question').setValue(this.sumTotal(index))
      this.getArr().at(index).get('total_random').setValue(this.sumTotal(index))
      this.test = this.getArr().value
    }
  }

  inputCheck(input,index,data,type){
    this.getArr().at(index).get(type).setValue(+input)
    this.getArr().at(index).get('total_random').setValue(this.sumTotal(index))
    this.checkValidation(index,data,type,input)
    this.isButtonDisabled.emit(this.checkCondition())
  }

  isNull(form){
    // const form = this.getArr().at(this.index).value
    // const form = this.getArr().value
    const isEnabledButton = form.total_random > 0
    // const multipleEasy = form.porranai_easy == 0? false : form.multiple_choice_easy == 0
    // const multipleMedium = form.porranai_medium == 0? false : form.multiple_choice_medium == 0
    // const multipleHard = form.porranai_hard == 0? false : form.multiple_choice_hard == 0
    // const subjectiveEasy = form.auttanai_easy == 0? false : form.subjective_easy == 0
    // const subjectiveMedium = form.auttanai_medium == 0? false : form.subjective_medium == 0
    // const subjectiveHard = form.auttanai_hard == 0? false : form.subjective_hard == 0
    // const conditionArray = [multipleEasy,multipleHard,multipleMedium,subjectiveEasy,subjectiveHard,subjectiveMedium]
    // const isEnabledButton = conditionArray.some(condition => condition == true)
    return isEnabledButton
  }

  checkCondition(){
    const form = this.getArr().value
    const conditionArray = form.map(data => this.isNull(data))
    const isEnabledButton = conditionArray.some(condition => condition == true)
    return !isEnabledButton
  }


}
