import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {MatTableDataSource} from '@angular/material/table';
import {FormBuilder, FormGroup, FormArray, Validators} from '@angular/forms';
import {TestingCenterService} from '../../../../core/service/TestingCenter/testing-center.service';
import {catchError, switchMap, tap} from 'rxjs/operators';
import {throwError} from 'rxjs';
import {SweetalertService} from '../../../../core/service/sweetalert/sweetalert';
import {ActivatedRoute, Router} from '@angular/router';
import {formatDate, Location} from '@angular/common';
import { BaseForm } from 'src/app/core/base/base-form';
import {BranchService} from '../../../../core/service/settings/branch.service';
import {TestingFieldService} from '../../../../core/service/settings/testing-field.service';
import {AcademicYearService} from '../../../../core/service/settings/academic-year.service';
import {AcademicSemesterService} from '../../../../core/service/settings/academic-semester.service';
import { MatDialog } from '@angular/material/dialog';
import { PreviewComponent } from '../dialog/preview/preview.component';

@Component({
  selector: 'app-manage-test-center-form',
  templateUrl: './manage-test-center-form.component.html',
  styleUrls: ['./manage-test-center-form.component.scss'],
  // changeDetection: ChangeDetectionStrategy.OnPush
})
export class ManageTestCenterFormComponent extends BaseForm implements OnInit {
  testcenterForm: FormGroup;
  PeriodData: any;
  // testingCenterPeriods: FormArray;
  // testingCenterRows: FormArray;
  UnivesityMock: any = [];
  TestfiledList:any = [];
  AcademicsemesterMock = [];
  AcademicYear = [];
  DataPriod: any = {
    period_id: null,
    start_time: '',
  };

  rowData: any = {
    row_name: '',
    no_of_seats: null,
  };

  jsonSection = [
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": "1",
      "start_time": "09:00"
    },
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": "2",
      "start_time": "12:00"
    },
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": "3",
      "start_time": "15:00"
    },
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": "4",
      "start_time": "18:00"
    }
  ];


  // public get getForm(): FormArray {
  //   return this.testcenterForm.get('testing_center_rows') as FormArray;
  // }

  displayedColumns: string[] = ['row_name', 'no_of_seats', 'actions'];
  displayedColumns2: string[] = ['period_id', 'start_time', 'actions'];
  dataSource = new MatTableDataSource();
  dataSource2 = new MatTableDataSource();
  constructor(
    private formBuilder: FormBuilder,
    private testingCenter: TestingCenterService,
    private branchSV: BranchService,
    private testfieldSV: TestingFieldService,
    private academicYearSV: AcademicYearService,
    private academicSemSV: AcademicSemesterService,
    private swSV: SweetalertService,
    public router: Router,
    public activeRoute: ActivatedRoute,
    public location: Location,
    private cdr: ChangeDetectorRef,
    private dialog: MatDialog
  ) {
    super(
      router,
      activeRoute,
      formBuilder,
      location
    );

    this.testcenterForm = this.formBuilder.group({
      status_id: 1,
      created_by: null,
      created_date: null,
      updated_by: null,
      updated_date: null,
      deleted_by: null,
      deleted_date: null,
      testing_field_uid: [null, Validators.required],
      testing_field_name_th: null,
      branch_uid: [null, Validators.required],
      branch_name_th: null,
      testing_room_name_th: [null, Validators.required],
      testing_room_name_en: [null],
      academic_year_uid:  [null, Validators.required],
      academic_semester_uid:  [null, Validators.required],
      testing_center_uid: null,
      testing_center_rows: this.formBuilder.array([
        this.rowForm()
      ]),
      testing_center_periods: this.formBuilder.array([
        this.periodsForm(),
      ]),
    });
  }

  periodsForm(a?){
    return this.formBuilder.group({
      status_id: 1,
      // created_by: null,
      // created_date: new Date(),
      // updated_by: null,
      // updated_date: Date,
      // deleted_by: null,
      // deleted_date: Date,
      testing_center_period_uid: null,
      // testing_center_id: null,
      period_id: [a?.period_id, Validators.required],
      start_time: [a?.start_time, Validators.required],
    });
  }
  periodsFormEdit(a){
    return this.formBuilder.group({
      status_id: a.status_id,
      created_by: a.created_by,
      created_date: a.created_date,
      updated_by: a.updated_by,
      updated_date: a.updated_date,
      deleted_by: a.deleted_by,
      deleted_date: a.deleted_date,
      testing_center_period_uid: a.testing_center_period_uid,
      testing_center_uid: a.testing_center_uid,
      period_id: a.period_id,
      start_time: a.start_time,
    });
  }
  rowForm(a?){
    return this.formBuilder.group({
      status_id: 1,
      // created_by: null,
      // created_date: new Date(),
      // updated_by: null,
      // updated_date: null,
      // deleted_by: null,
      // deleted_date: null,
      testing_center_row_uid: null,
      // testing_center_id: null,
      row_name: [a?.row_name, Validators.required],
      no_of_seats: [a?.no_of_seats,
        [Validators.pattern(/^-?(0|[1-9]\d*)?$/) , Validators.required],
      ],
    });
  }
  rowFormEdit(a){
    return this.formBuilder.group({
      status_id: a.status_id,
      created_by: a.created_by,
      created_date: a.created_date,
      updated_by: a.updated_by,
      updated_date: a.updated_date,
      deleted_by: a.deleted_by,
      deleted_date: a.deleted_date,
      testing_center_row_uid: a.testing_center_row_uid,
      testing_center_uid: a.testing_center_uid,
      row_name: a.row_name,
      no_of_seats: a.no_of_seats,
    });
  }

  ngOnInit(): void {

    this.branchSV.getAllStatus1().pipe(
      tap(x => this.UnivesityMock = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe()

    this.testfieldSV.getAll().pipe(
      tap(x => this.TestfiledList = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe()

    this.academicYearSV.getAll().pipe(
      tap(x => this.AcademicYear = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe()

    this.academicSemSV.getAll().pipe(
      tap(x => this.AcademicsemesterMock = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe()

    switch (this.state) {
      case 'edit':
        const formRow = this.testcenterForm.get('testing_center_rows') as FormArray;
        const formPeriod = this.testcenterForm.get('testing_center_periods') as FormArray;
        this.testingCenter.get(this.id).pipe(
          tap(x => console.log(x)),
          tap(x => this.testcenterForm.patchValue(x)),
          tap(x => {
            formRow.clear();
            // @ts-ignore
            x.testing_center_rows.forEach(a => {
              console.log(a);
              formRow.push(this.rowFormEdit(a));
              // formPeriod.push(this.formBuilder.group(a));
            });
            const table = formRow.getRawValue();
            this.dataSource.data = table;
          }),
          tap(x => {
            formPeriod.clear();
            // @ts-ignore
            x.testing_center_periods.forEach(a => {
              console.log(a);
              formPeriod.push(this.periodsFormEdit(a));
              // formPeriod.push(this.formBuilder.group(a));
            });
            const table = formPeriod.getRawValue();
            this.dataSource2.data = table;
          }),
          tap(x => this.cdr.detectChanges())
        ).subscribe();
        break;
      case 'add':
        console.log(this.jsonSection);
        const formPeriodAdd = this.testcenterForm.get('testing_center_periods') as FormArray;
        formPeriodAdd.clear();
        this.jsonSection.forEach(a => {
          formPeriodAdd.push(this.periodsForm(a));
        });
        // this.rowForm(this.jsonSection);
        break;
    }
    // const form1 = this.testcenterForm.get('testing_center_rows') as FormArray;
    // form1.reset();
    // const form2 = this.testcenterForm.get('testing_center_periods') as FormArray;
    // form2.reset();
    // this.dataSource.data = [];
    // this.dataSource2.data = [];
  }

  save(){
    const form = this.testcenterForm.getRawValue();
    const formRow = this.testcenterForm.get('testing_center_rows') as FormArray;
    const formPeriod = this.testcenterForm.get('testing_center_periods') as FormArray;
    switch (this.state) {
      case 'edit':
        form.created_datetime = formatDate(new Date(), 'yyyy-MM-dd', 'en-US');
        this.testingCenter.update2(form).pipe(
          tap(x => this.swSV.updateSuccess()),
          tap(x => window.history.back()),
          catchError(err => {
            this.swSV.errText(err.error.description);
            return throwError(err);
          })
        ).subscribe();
        break;
      case 'add':
        this.testingCenter.add(form).pipe(
          tap(x => this.swSV.saveSuccess()),
          tap(x => window.history.back()),
          catchError(err => {
            this.swSV.errText(err.error.description);
            return throwError(err);
          })
        ).subscribe();
        break;
    }
  }

  clearTable() {
    this.dataSource.data = [];
  }

  // addItem(){
  //   this.getForm.push(this.rowForm());
  // }
  // remove(index: number){
  //   this.getForm.removeAt(index);
  // }
  addData() {
    this.dataSource.data = [];
  }

  clearTable2() {
    this.dataSource2.data = [];
  }
  addData2() {
    this.dataSource2.data = [];
  }

  putArray(){
    const form = this.testcenterForm.get('testing_center_rows') as FormArray;
    const table = form.getRawValue();
    this.dataSource.data = table;
  }
  add(){
    const form = this.testcenterForm.get('testing_center_rows') as FormArray;
    form.push(this.rowForm());
  }

  removeArray(i){
    const form = this.testcenterForm.get('testing_center_rows') as FormArray;
    form.removeAt(i);
  }

  removeArrayTable(i){
    const form = this.testcenterForm.get('testing_center_rows') as FormArray;
    form.removeAt(i);
    const table = form.getRawValue();
    this.dataSource.data = table;
  }

  add2(){
    const form = this.testcenterForm.get('testing_center_periods') as FormArray;
    form.push(this.periodsForm());
  }

  putArray2(){
    const form = this.testcenterForm.get('testing_center_periods') as FormArray;
    const table = form.getRawValue();
    this.dataSource2.data = table;
  }

  removeArray2(i){
    const form = this.testcenterForm.get('testing_center_periods') as FormArray;
    form.removeAt(i);
    const table = form.getRawValue();
    this.dataSource2.data = table;
  }


  cancel(){
    window.history.back()
  }

  setTestField(id){
    this.testfieldSV.getByBrandID(id).pipe(
      tap(x => console.log(x)),
      tap(x => this.TestfiledList = x),
    ).subscribe();
  }

  preview(){
    const form = (this.testcenterForm.get('testing_center_rows') as FormArray).getRawValue();
    const obj = {
      data : form,
      testing_center: this.testcenterForm.getRawValue()
    }

    const dialogRef = this.dialog.open(PreviewComponent, {
      width: '600px',
      maxHeight: '80vh',
      data: obj
    });
  }
}
