import {Component, OnInit, ChangeDetectionStrategy, Inject, ChangeDetectorRef} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {FormArray, FormBuilder, Validators} from '@angular/forms';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {TestingCenterService} from '../../../../../core/service/TestingCenter/testing-center.service';
import {catchError, tap} from 'rxjs/operators';
import {throwError} from 'rxjs';
import {TestingInformationService} from '../../../../../core/service/testing-information/testing-information.service';
import {BaseForm} from '../../../../../core/base/base-form';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';

@Component({
  selector: 'app-set-exam-information-dialog',
  templateUrl: './set-exam-information-dialog.component.html',
  styleUrls: ['./set-exam-information-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SetExamInformationDialogComponent extends BaseForm implements OnInit {
  displayedColumns: string[] = ['1', '2', '3', '4', '5'];
  dataSource;
  form;
  default = true;
  rowsdata;
  ishidden = false;
  constructor(
    private TestcenterSV: TestingCenterService,
    private TestInformationSV: TestingInformationService,
    private formBuilder: FormBuilder,
    private swSV: SweetalertService,
    private cdf: ChangeDetectorRef,
    public router: Router,
    public activeRoute: ActivatedRoute,
    public location: Location,
    private dialogRef: MatDialogRef<SetExamInformationDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data
  ) {
    super(
      router,
      activeRoute,
      formBuilder,
      location
    );
    this.form = this.formBuilder.group({
      testing_seat: this.formBuilder.array([
        this.testing_seat()
      ])
    });
  }
  testing_seat(data?){
    return this.formBuilder.group({
      testing_seat_uid: data?.testing_seat_uid,
      status_id: data?.status_id,
      // created_by: null,
      // created_datetime: null,
      // updated_by: null,
      // updated_datetime: null,
      // deleted_by: null,
      // deleted_datetime: null,
      testing_center_row_uid: data?.testing_center_row_uid,
      // is_specify_subject: data?.is_specify_subject,
      is_specify_subject: data?.is_specify_subject !==  undefined ? data?.is_specify_subject : false,
      testing_room_uid: data?.testing_room_uid,
      row_name: [data?.row_name, Validators.required],
      no_of_seats: [data?.no_of_seats, Validators.required],
      testing_seat_subjects: this.formBuilder.array([
        this.testing_seat_subjects(data?.testing_seat_subjects)
      ])
    });

  }

  testing_seat_subjects(data?){
    // console.log(data)
    return this.formBuilder.group({
      testing_seat_uid: data?.testing_seat_uid,
      status_id: null,
      testing_seat_subject_uid: data?.testing_seat_subject_uid,
      subject_uid: data?.subject_uid,
      subject_code: data?.subject_code,
      subject_name_th: data?.subject_name_th,
      start_seat_no: [data?.start_seat_no, [Validators.required , Validators.min]],
      end_seat_no: [data?.end_seat_no, [Validators.required , Validators.min]],
    });
  }

  ngOnInit(): void {
    console.log(this.data);
    // this.dataSource = this.data.subjectlist;
    const form = this.form.get('testing_seat') as FormArray;
    form.clear();
    const form2 = this.form.get('testing_seat_subjects') as FormArray;
    // console.log( form.insert(1,));
    // const form2 = form.get('control')('testing_seat_subjects') as FormArray;
    // console.log(form2);
    // for (let i = 0; i < this.data.subjectlist.length; i++) {
    //   console.log(i);
    //   const formArray3 = form.controls[i].get('testing_seat_subjects') as FormArray;
    //   console.log(formArray3);
    //   formArray3.push(this.testing_seat_subjects((this.data.subjectlist[i])));
    // }
    switch (this.data.state) {
      case 'add': {
        this.TestcenterSV.get(this.data.id).subscribe(
          result => {
            // console.log(result);
            this.rowsdata = result;
            // console.log(this.rowsdata.testing_center_rows);
            form.clear();
            for (let i = 0; i < this.rowsdata.testing_center_rows.length; i++) {
              // console.log(typeof this.rowsdata.testing_center_rows[i].no_of_seats);
              form.push(this.testing_seat((this.rowsdata.testing_center_rows[i])));
              const formArray3 = form.controls[i].get('testing_seat_subjects') as FormArray;
              formArray3.removeAt(0);
              for (let i = 0; i < this.data.subjectlist.length; i++) {
                // console.log(i);
                // console.log(formArray3);
                // console.log(this.data.subjectlist[i]);
                formArray3.push(this.testing_seat_subjects((this.data.subjectlist[i])));
              }
            }
            this.cdf.detectChanges();
          }
        );
        break;
      }
      case 'edit': {
        // console.log(this.data);
        console.log(this.data.id);
        this.rowsdata = this.data.centerList;
        console.log(this.rowsdata);
        if (this.rowsdata.testing_seats[0].testing_center_row_uid !== null){
          for (let i = 0 ; i < this.rowsdata.testing_seats.length ; i++){
            form.push(this.testing_seat(this.rowsdata.testing_seats[i]));
            const formArray3 = form.controls[i].get('testing_seat_subjects') as FormArray;
            formArray3.clear();
            for (let j = 0; j < this.rowsdata.testing_seats[i].testing_seat_subjects.length; j++){
              formArray3.push(this.testing_seat_subjects((this.rowsdata.testing_seats[i].testing_seat_subjects[j])));
            }
          }
          break;
        }else {
          this.TestcenterSV.get(this.data.id).subscribe(
            result => {
              this.rowsdata = result;
              form.clear();
              // console.log(this.rowsdata.testing_center_rows);
              for (let i = 0; i < this.rowsdata.testing_center_rows.length; i++) {
                form.push(this.testing_seat((this.rowsdata.testing_center_rows[i])));
                const formArray3 = form.controls[i].get('testing_seat_subjects') as FormArray;
                formArray3.removeAt(0);
                // for (let i = 0; i < this.data.subjectlist.length; i++) {
                  // console.log(i);
                  // console.log(formArray3);
                  // console.log(this.data.subjectlist[i]);
                  // formArray3.push(this.testing_seat_subjects((this.data.subjectlist[i])));
                // }
              }
              this.cdf.detectChanges();
            }
          );
          break;
        }
      }
      case 'view': {
        // console.log(this.data);
        console.log(this.data.id);
        this.rowsdata = this.data.centerList;
        console.log(this.rowsdata);
        if (this.rowsdata.testing_seats[0].testing_center_row_uid !== null){
          for (let i = 0 ; i < this.rowsdata.testing_seats.length ; i++){
            console.log(this.rowsdata.testing_seats[i]);
            form.push(this.testing_seat(this.rowsdata.testing_seats[i]));
            const formArray3 = form.controls[i].get('testing_seat_subjects') as FormArray;
            formArray3.clear();
            for (let j = 0; j < this.rowsdata.testing_seats[i].testing_seat_subjects.length; j++){
              console.log(this.rowsdata.testing_seats[i].testing_seat_subjects[j]);
              formArray3.push(this.testing_seat_subjects((this.rowsdata.testing_seats[i].testing_seat_subjects[j])));
            }
          }
          break;
        }else {
          this.TestcenterSV.get(this.data.id).subscribe(
            result => {
              console.log(result);
              this.rowsdata = result;
              form.clear();
              // console.log(this.rowsdata.testing_center_rows);
              for (let i = 0; i < this.rowsdata.testing_center_rows.length; i++) {
                console.log(typeof this.rowsdata.testing_center_rows[i].no_of_seats);
                form.push(this.testing_seat((this.rowsdata.testing_center_rows[i])));
                const formArray3 = form.controls[i].get('testing_seat_subjects') as FormArray;
                formArray3.removeAt(0);
                for (let i = 0; i < this.data.subjectlist.length; i++) {
                  // console.log(i);
                  // console.log(formArray3);
                  // console.log(this.data.subjectlist[i]);
                  formArray3.push(this.testing_seat_subjects((this.data.subjectlist[i])));
                }
              }
              this.cdf.detectChanges();
            }
          );
          break;
        }
      }
    }
    this.dataSource = this.data.subjectlist;
  }

  save(){
    const form = this.form;
    this.dialogRef.close({ event: 'close', data: form });
  }

  cancel(){
    this.dialogRef.close();
  }

  settestingseat(i, boolean: boolean){
    const form = this.form.get('testing_seat') as FormArray;
    const form2 = form.controls[i].get('testing_seat_subjects') as FormArray;
    // switch (boolean) {
    //   case true: {
    //     form2.clear();
    //     break;
    //   }
    //   case false: {
    //     if (form2.getRawValue().length === 0){
    //       form2.clear();
    //       for (i = 0; i < this.data.subjectlist.length; i++) {
    //         console.log(i);
    //         console.log(form2);
    //         form2.push(this.testing_seat_subjects((this.data.subjectlist[i])));
    //       }
    //     }
    //     break;
    //   }
    //
    // }
    // console.log(form2.getRawValue());
    if (boolean === false){
      form2.clear();
    }
    if (boolean === true){
      if (form2.getRawValue().length === 0){
        form2.clear();
        for (i = 0; i < this.data.subjectlist.length; i++) {
          form2.push(this.testing_seat_subjects((this.data.subjectlist[i])));
        }
      }
    }
  }

  displayValue(data){
    console.log(data)
    return true;
  }

  checkInput(data, indexFormTestSeat, indexFormSeatSubject){
    const form = this.form.get('testing_seat') as FormArray;
    const formArray = form.at(indexFormTestSeat).get('testing_seat_subjects') as FormArray;
    if (formArray.at(indexFormSeatSubject).get('start_seat_no').value === null && formArray.at(indexFormSeatSubject).get('end_seat_no').value !== null){
      formArray.at(indexFormSeatSubject).get('end_seat_no').setValue(null);
    }
  }

  checkInputMax(data, indexFormTestSeat, indexFormSeatSubject){

  }

}
