import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {
  TestingInformationService
} from '../../../../../../core/service/testing-information/testing-information.service';
import {BaseList} from '../../../../../../core/base/base-list';
import {catchError, concatMap, filter, tap} from 'rxjs/operators';
import {MatDialog} from '@angular/material/dialog';
import {
  DialogCreatePeriodByDayComponent
} from '../../dialog/dialog-create-period-by-day/dialog-create-period-by-day.component';
import {
  TestingSubjectAddDateService
} from '../../../../../../core/service/testing-information/testing-subject-add-date.service';
import {throwError} from "rxjs";
import {SweetalertService} from "../../../../../../core/service/sweetalert/sweetalert";

@Component({
  selector: 'app-setup-period-by-subject-infor',
  templateUrl: './setup-period-by-subject-infor.component.html',
  styleUrls: ['./setup-period-by-subject-infor.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SetupPeriodBySubjectInforComponent extends BaseList implements OnInit {
  testInforId: any;
  testsubjectId: any;
  subjectList: any = [];
  subjectDetail: any = [];
  query = {
    testing_subject_uid: null,
    testing_information_uid: null,
  };
  column = ['0', '1', '2', '3'];
  constructor(
    private dialog: MatDialog,
    private router: Router,
    private activeRouter: ActivatedRoute,
    private TestinforSV: TestingInformationService,
    private TestSubjectAddDateSV: TestingSubjectAddDateService,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService
  ) {
    super();
  }

  ngOnInit(): void {
    this.activeRouter.params.pipe(
      // tap(x => x.id ? this.state = 'edit' : this.state = 'add'),
      tap(x => console.log(x)),
      tap(x => x.testInforId ? this.testInforId = x.testInforId : this.testInforId = null),
      tap(x => x.testInforId ? this.query.testing_information_uid = x.testInforId : this.query.testing_information_uid = null),
      tap(x => x.subjectId ? this.testsubjectId = x.subjectId : this.testsubjectId = null),
      tap(x => x.subjectId ? this.query.testing_subject_uid = x.subjectId : this.query.testing_subject_uid = null),
      tap(x =>
        this.TestinforSV.get(x.testInforId).pipe(
          tap(y => {
            const data: any = y;
            this.subjectDetail = data.testing_subjects.filter(x => {
              return x.testing_subject_uid === this.testsubjectId;
            });
            // this.subjectDetail = this.updateMatTable(data.testing_subjects ? data.testing_subjects : []);
          }),
          tap(y => console.log(this.subjectDetail)),
          tap(y => this.cdr.detectChanges()),
        ).subscribe()
      ),
      tap(x =>
        this.TestSubjectAddDateSV.search(`?${this.createQueryStringFromObject(this.query)}`).pipe(
          tap(y => {
            const data: any = y;
            console.log(data);
            this.subjectDetail = data;
            // this.subjectDetail = data.testing_subjects.filter(x => {
            //   return x.testing_subject_uid === this.testsubjectId;
            // });
            this.subjectList = this.updateMatTable(data ? data : []);
          }),
          tap(y => console.log(this.subjectList)),
          tap(y => this.cdr.detectChanges()),
        ).subscribe()
      ),
    ).subscribe();
  }

  onAdd(){
    const dialogRef = this.dialog.open(DialogCreatePeriodByDayComponent, {
      width: '700px',
      height: '350px',
      data: {
        testInforId : this.testInforId,
        testsubjectId : this.testsubjectId,
        state : 'add',
      }
    });
    dialogRef.afterClosed().pipe(
      tap(x => console.log(x)),
      tap(x => {
        this.TestSubjectAddDateSV.search(`?${this.createQueryStringFromObject(this.query)}`).pipe(
          tap(y => {
            const data: any = y;
            this.subjectList = this.updateMatTable(data ? data : []);
          }),
          tap(y => this.cdr.detectChanges()),
        ).subscribe();
      }),
    ).subscribe();
  }

  onEdit(id){
    const dialogRef = this.dialog.open(DialogCreatePeriodByDayComponent, {
      width: '700px',
      height: '350px',
      data: {
        testInforId : this.testInforId,
        testsubjectId : this.testsubjectId,
        testingSubjectAddDateId : id,
        state : 'edit',
      }
    });
    dialogRef.afterClosed().pipe(
      tap(x => console.log(x)),
      tap(x => {
        this.TestSubjectAddDateSV.search(`?${this.createQueryStringFromObject(this.query)}`).pipe(
          tap(y => {
            const data: any = y;
            this.subjectList = this.updateMatTable(data ? data : []);
          }),
          tap(y => this.cdr.detectChanges()),
        ).subscribe();
      }),
    ).subscribe();
  }

  onDelete(id){
    this.swSV.confirm().pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        return this.TestSubjectAddDateSV.deleteData(id).pipe(
          tap(x => this.swSV.removeSuccess()),
          tap(x => {
            this.TestSubjectAddDateSV.search(`?${this.createQueryStringFromObject(this.query)}`).pipe(
              tap(y => {
                const data: any = y;
                this.subjectList = this.updateMatTable(data ? data : []);
              }),
              tap(y => this.cdr.detectChanges()),
            ).subscribe();
          }),
          catchError(err => {
            this.swSV.errText(err.error);
            return throwError(err);
          })
        );
      })
    ).subscribe();
  }

  createQueryStringFromObject = (object: any):string => {
    let queryStr: string = ''

    for (const key in object) {
      if (object[key]) {
        queryStr += `${key}=${object[key]}&`
      }
    }
    let lastIndex = queryStr.lastIndexOf('&')
    queryStr = queryStr.slice(0,lastIndex)
    return queryStr
  }

}
