import { Location } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { FormArray, FormBuilder, RequiredValidator, Validators } from '@angular/forms';
import { MatGridTileHeaderCssMatStyler } from '@angular/material/grid-list';
import { ActivatedRoute, Router } from '@angular/router';
import { of, throwError } from 'rxjs';
import { catchError, concatMap, filter, tap } from 'rxjs/operators';
import { BaseForm } from 'src/app/core/base/base-form';
import { BaseFormUid } from 'src/app/core/base/base-form-uid';
import { QuestionCategoryService } from 'src/app/core/service/question/question-category.service';
import { SubjectsService } from 'src/app/core/service/settings/subjects.service';
import { SubjectInformationService } from 'src/app/core/service/store-api/subject-information.service';
import { SyncStoreService } from 'src/app/core/service/store-api/sync.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { RandomQuestionsService } from 'src/app/core/service/testing-information/random-questions.service';

@Component({
  selector: 'app-random-questions-form',
  templateUrl: './random-questions-form.container.html',
  styleUrls: ['./random-questions-form.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RandomQuestionsFormContainer extends BaseFormUid implements OnInit {
  questionCategory;
  questionCategoryAll;
  questionCategoryInstructor;
  questionCategoryType;
  data;
  subject;
  subjectInformation;
  oldData;
  buttonDisabled: boolean = false
  constructor(
    public fb: FormBuilder,
    public router: Router,
    public activeRoute: ActivatedRoute,
    public location: Location,
    private questionCategoryDetailSV: QuestionCategoryService,
    private cdr: ChangeDetectorRef,
    private subjectSV: SubjectsService,
    private randomQuestionSV: RandomQuestionsService,
    private swSV: SweetalertService,
    private subjectInformationSV : SubjectInformationService,
    private syncSV: SyncStoreService
  ) {
    super(router,activeRoute,fb,location)
   }

  ngOnInit(): void {
    if(this.state == 'edit'){
      this.activeRoute.paramMap.pipe(
        concatMap((x:any) => this.randomQuestionSV.search('?subject_uid='+x.params.id+'&testing_information_uid='+x.params.uid+'&is_use=true')),
        concatMap((x:any) => {
          if(x.length > 0) {
            return this.randomQuestionSV.get(x[0].random_question_uid)
          } else {
            return of()
          }
        }),
        tap((x:any) => this.oldData = x),
      ).subscribe()
      this.questionCategoryDetailSV.getSubject(this.id).pipe(
        tap(x => this.questionCategory = x),
        concatMap((x:any) => this.subjectInformationSV.get(x[0].subject_information_uid)),
        tap(x => this.subjectInformation = x),
      ).subscribe()
      this.questionCategoryDetailSV.search('?subject_uid='+this.id+'&level=0').pipe(
        tap((x:any) => this.questionCategoryType = x.filter((v,i,a) => a.findIndex(b => b.question_category_master_uid == v.question_category_master_uid) === i))
      ).subscribe()
      this.questionCategoryDetailSV.getAllSubject(this.id).pipe(
        tap(x => this.questionCategoryAll = x),
      ).subscribe()
      this.questionCategoryDetailSV.getSubjectWithInstructor(this.id).pipe(
        tap(x => this.questionCategoryInstructor = x)
      ).subscribe()
      this.subjectSV.get(this.id).pipe(
        tap(x => this.subject = x),
        tap(x => this.cdr.detectChanges())
      ).subscribe()
      this.form.get('subject_uid').setValue(this.id)
      this.activeRoute.params.pipe(
        tap(x => this.form.get('testing_information_uid').setValue(x.uid))
      ).subscribe()
    }
  }

  createForm(){
    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_uid: null,
      testing_information_uid: null,
      subject_uid: null,
      random_type: [null,Validators.required],
      random_question_type: [null,Validators.required],
      time_to_complete_exam: [null,Validators.required],
      random_question_details: this.fb.array([]),
      array: this.fb.array([
        this.createArray()
      ])
    })
  }

  questionTypeChange(event){
    this.buttonDisabled = false
    const form = this.form.get('array') as FormArray
    const random = this.form.get('random_question_details') as FormArray
    if(event.value == 3){
      form.clear()
      random.clear()
      random.push(this.createInstructorForm())
      this.form.get('time_to_complete_exam').setValidators(Validators.required)
      this.form.get('time_to_complete_exam').updateValueAndValidity()
    } else if (event.value == 1){
      form.clear()
      random.clear()
      random.push(this.createGroupForm())
      this.form.get('time_to_complete_exam').clearValidators()
      this.form.get('time_to_complete_exam').updateValueAndValidity()
    } else{
      form.clear()
      random.clear()
      this.form.get('time_to_complete_exam').setValidators(Validators.required)
      this.form.get('time_to_complete_exam').updateValueAndValidity
      form.push(this.createArray())
    }
  }

  randomTypeChange(event){
    const form = this.form.get('array') as FormArray
    const random = this.form.get('random_question_details') as FormArray
    form.clear()
    random.clear()
    this.form.get('random_question_type').setValue(null)
  }

  createArray(){
    return this.fb.group({
      arr: this.fb.array([],Validators.required)
    })
  }

  addTeacher(){
    const form = this.form.get('random_question_details') as FormArray
    form.push(this.createInstructorForm())
  }

  removeTeacher(index){
    const form = this.form.get('random_question_details') as FormArray
    form.removeAt(index)
  }

  createGroupForm(){
    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: [null,Validators.required],
      total_question: [0,Validators.required],
      question_sub_set_uid: null,
      total_question_easy: [null],
      total_question_medium: [null],
      total_question_hard: [null],
      instructor_uid: [null],
      instructor_name: null,
      num_question: null,
      exam_time: [null,Validators.required],
      row_order: null,
      total_question_porranai: null,
      total_question_auttanai: null
    })
  }

  createInstructorForm(){
    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: null,
      total_question: [null,Validators.required],
      question_sub_set_uid: null,
      total_question_easy: [null],
      total_question_medium: [null],
      total_question_hard: [null],
      instructor_uid: [null,Validators.required],
      instructor_name: null,
      num_question: null,
      row_order: null,
      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],
      total_question_auttanai_easy: null,
      total_question_porranai_easy: null,
      total_question_auttanai_medium: null,
      total_question_porranai_medium: null,
      total_question_auttanai_hard: null,
      total_question_porranai_hard: null,
      total_question_porranai: null,
      total_question_auttanai: null,
    })
  }


  addCategory(){
    const form = this.form.get('array') as FormArray
    form.push(this.createArray())
  }

  addGroup(){
    const form = this.form.get('random_question_details') as FormArray
    form.push(this.createGroupForm())
  }

  save(){
    const teacherForm = this.form.getRawValue()
    teacherForm.random_question_details.map((data,index) => {
      data.row_order = index+1
    })
    if(this.oldData){
      teacherForm.random_question_uid = this.oldData.random_question_uid
    }

    this.swSV.confirmWithSubtext('ผู้เข้าสอบที่ยังไม่ได้สอบจะถูกลบข้อมูลการสุ่มเดิมและแทนที่ด้วยลักษณะการสุ่มนี้','กรุณากดสร้างข้อสอบใหม่ทุกครั้งหลังจากเปลี่ยนเงื่อนไข').pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        if(teacherForm.random_question_type == 3){
          if(this.oldData){
            return this.randomQuestionSV.update2(teacherForm).pipe(
              tap(x => this.swSV.saveSuccess()),
              tap(x => this.location.back()),
              catchError(err => {
                this.swSV.err()
                return throwError(err)
              })
            )
          }else{
            return this.randomQuestionSV.add(teacherForm).pipe(
              tap(x => this.swSV.saveSuccess()),
              tap(x => this.location.back()),
              catchError(err => {
                this.swSV.err()
                return throwError(err)
              })
            )
          }
        }else if (teacherForm.random_question_type == 1){
          if(this.oldData){
            return this.randomQuestionSV.update2(teacherForm).pipe(
              tap(x => this.swSV.saveSuccess()),
              tap(x => this.location.back()),
              catchError(err => {
                this.swSV.err()
                return throwError(err)
              })
            )
          } else {
            return this.randomQuestionSV.add(teacherForm).pipe(
              tap(x => this.swSV.saveSuccess()),
              tap(x => this.location.back()),
              catchError(err => {
                this.swSV.err()
                return throwError(err)
              })
            )
          }
        }else{
          let newdata = []
          const saveForm = this.form.getRawValue()
          const arr = this.form.get('array') as FormArray
          const form = arr.getRawValue()
          form.map(x => {
            x.arr.map(a => newdata.push(a))
          })
          newdata.map((data,index) => {
            data.row_order = index+1
          })
          saveForm.random_question_details = newdata;
          if(this.oldData){
            saveForm.random_question_uid = this.oldData.random_question_uid
            return this.randomQuestionSV.update2(saveForm).pipe(
              tap(x => this.swSV.saveSuccess()),
              tap(x => this.location.back()),
              catchError(err => {
                this.swSV.err()
                return throwError(err)
              })
            )
          }else{
            return this.randomQuestionSV.add(saveForm).pipe(
              tap(x => this.swSV.saveSuccess()),
              tap(x => this.location.back()),
              catchError(err => {
                this.swSV.err()
                return throwError(err)
              })
            )
          }
        }
      }),
      concatMap(x => {
        return this.syncSV.deleteTest(teacherForm.testing_information_uid,teacherForm.subject_uid)
      })
    ).subscribe()
  }

  cancel(){
    this.location.back()
  }

  removeCategory(index){
    const form = this.form.get('array') as FormArray
    form.removeAt(index)
  }

  removeGroup(index){
    const form = this.form.get('random_question_details') as FormArray
    form.removeAt(index)
  }

}
