import {Component, OnInit, ChangeDetectionStrategy, Inject, ChangeDetectorRef} from '@angular/core';
import {FormArray, FormBuilder} from "@angular/forms";
import {CalendarTypeService} from "../../../../../../core/service/settings/calendar-type.service";
import {SweetalertService} from "../../../../../../core/service/sweetalert/sweetalert";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog";
import {catchError, tap} from "rxjs/operators";
import {throwError} from "rxjs";
import {
  TestingInformationService
} from "../../../../../../core/service/testing-information/testing-information.service";
import {
  TestingSubjectAddDateService
} from "../../../../../../core/service/testing-information/testing-subject-add-date.service";
import {Location} from '@angular/common';


@Component({
  selector: 'app-dialog-create-period-by-day',
  templateUrl: './dialog-create-period-by-day.component.html',
  styleUrls: ['./dialog-create-period-by-day.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DialogCreatePeriodByDayComponent implements OnInit {
  form;
  startDate;
  endDate;
  sectionsFakeFalse = [
    {
      status_id: 1,
      testing_center_period_uid: null,
      period_id: 1,
      is_check: false,
      start_time: '09:00'
    },
    {
      status_id: 1,
      testing_center_period_uid: null,
      period_id: 2,
      is_check: false,
      start_time: '12:00'
    },
    {
      status_id: 1,
      testing_center_period_uid: null,
      period_id: 3,
      is_check: false,
      start_time: '15:00'
    },
    {
      status_id: 1,
      testing_center_period_uid: null,
      period_id: 4,
      is_check: false,
      start_time: '18:00'
    }
  ];
  constructor(
    private fb: FormBuilder,
    private TestInformationSV: TestingInformationService,
    private TestSubjectAddDateSV: TestingSubjectAddDateService,
    private calendarSV: CalendarTypeService,
    private cdr: ChangeDetectorRef,
    public location: Location,
    private swSV: SweetalertService,
    private dialogRef: MatDialogRef<DialogCreatePeriodByDayComponent>,
    @Inject(MAT_DIALOG_DATA) public data
  ) {
    this.form = this.fb.group({
      status_id: 1,
      create_by: null,
      created_datetime: null,
      updated_by: null,
      updated_datetime: null,
      deleted_by: null,
      deleted_datetime: null,
      testing_date: null,
      testing_subject_uid: null,
      testing_subject_add_date_uid: null,
      period: this.fb.array([
        this.testing_periods()
      ])
    });
  }

  testing_periods(data?){
    return this.fb.group({
      status_id: 1,
      create_by: null,
      created_datetime: null,
      updated_by: null,
      updated_datetime: null,
      deleted_by: null,
      deleted_datetime: null,
      is_check: data?.is_check,
      testing_information_uid: data?.testing_information_uid,
      testing_period_uid: data?.testing_period_uid,
      period_id: data?.period_id,
      start_time: data?.start_time,
    });
  }

  ngOnInit(): void {
    const form = this.form.get('period') as FormArray;
    console.log(this.data);
    switch (this.data.state) {
      case 'edit':
        form.clear();
        // this.form.get('testing_subject_uid').setValue(this.data.testsubjectId);
        // this.form.get('testing_subject_add_date_uid').setValue(this.data.testingSubjectAddDateId);
        this.TestSubjectAddDateSV.get(this.data.testingSubjectAddDateId).pipe(
          tap(x => console.log(x)),
          tap(x => this.form.patchValue(x)),
          tap(x => this.editPeriodEdit(x)),
        ).subscribe();
        break;
      case 'add':
        form.clear();
        this.form.get('testing_subject_uid').setValue(this.data.testsubjectId);
        this.TestInformationSV.get(this.data.testInforId).pipe(
          tap(x => {
            console.log(x);
            const data: any = x;
            this.startDate = data.testing_start_datetime;
            this.endDate = data.testing_end_datetime;
          }),
          tap(x => this.addPeriodEdit(x)),
        ).subscribe();
        break;
    }
  }

  editPeriodEdit(x){
    const form = this.form.get('period') as FormArray;
    const Array = x.period;
    console.log(Array);
    this.TestInformationSV.get(this.data.testInforId).pipe(
      tap(x => {
        const data: any = x;
        this.startDate = data.testing_start_datetime;
        this.endDate = data.testing_end_datetime;
        // Filter Array By Array
        // const res = Array.findIndex(item1 =>
        //   !!data.testing_periods.find(item2 => item1 === item2.period_id)
        // );
        for (let i = 0; i < data.testing_periods.length; i++){
          form.push(this.testing_periods(data.testing_periods[i]));
        }
      }),
      tap(x => {
        for (let i = 0; i < Array.length; i++){
          const foundIndex = form.getRawValue().findIndex(v => v.period_id === Array[i]);
          if (foundIndex !== null){
            form.at(foundIndex).get('is_check').setValue(true);
          }
        }

      }),
    ).subscribe();
  }

  addPeriodEdit(x){
    const form = this.form.get('period') as FormArray;
    const Array = x.testing_periods;

    const SortArray =  Array.sort((a, b) => a.period_id - b.period_id);
    console.log(SortArray);

    for (let i = 0; i < SortArray.length; i++) {
      // const foundIndex = this.sectionsFakeFalse.findIndex(v => v.period_id === x.testing_periods[i].period_id);
      // this.sectionsFakeFalse[foundIndex].is_check = true;
      // this.sectionsFakeFalse[foundIndex].start_time = x.testing_periods[i].start_time;
      console.log(SortArray[i]);
      form.push(this.testing_periods(SortArray[i]));
    }
  }

  save(){
    const form = this.form.getRawValue()
    form.period = form.period.filter((member) => {
      return member.is_check === true;
    });
    const PeriodList = form.period.filter((member) => {
      return member.is_check === true;
    });
    const period: any = [];
    console.log(PeriodList);
    for (let i = 0; i < PeriodList.length; i++) {
      period.push(PeriodList[i].period_id)
    }
    // form.testing_periods.clear()
    form.period = period;
    // const sendData = form;
    switch (this.data.state) {
      case 'edit':
        console.log(form)
        this.TestSubjectAddDateSV.update2(form).pipe(
          tap(x => this.swSV.saveSuccess()),
          tap(x => this.cdr.detectChanges()),
          tap(x =>  this.dialogRef.close('success')),
          // tap(x => this.location.back()),
          catchError(err => {
            this.swSV.err()
            return throwError(err)
          })
        ).subscribe();
        break;
      case 'add':
        console.log(form)
        this.TestSubjectAddDateSV.add(form).pipe(
          tap(x => this.swSV.saveSuccess()),
          tap(x => this.cdr.detectChanges()),
          tap(x =>  this.dialogRef.close('success')),
          // tap(x => this.location.back()),
          catchError(err => {
            this.swSV.err()
            return throwError(err)
          })
        ).subscribe();
        break;
    }
  }

  cancel(){
    this.dialogRef.close('success')
  }



}
