import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {Observable, throwError} from 'rxjs';
import {Router} from '@angular/router';
import {TestingInformationService} from '../../../../../core/service/testing-information/testing-information.service';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {catchError, concatMap, filter, tap} from "rxjs/operators";
import {MatDialog} from '@angular/material/dialog';
import {
  NotificationCheckExamDialogComponent
} from '../../../../notification-check-exam/presenter/notification-check-exam/dialog/notification-check-exam-dialog/notification-check-exam-dialog.component';
import {ConfirmRejectExamDialogComponent} from '../../presenter/dialog/confirm-reject-exam-dialog/confirm-reject-exam-dialog.component';


@Component({
  selector: 'app-reject-exam',
  templateUrl: './reject-exam.container.html',
  styleUrls: ['./reject-exam.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RejectExamContainer implements OnInit {

  subjectList$ = new Observable();
  constructor(
    private router: Router,
    private TestinforSV: TestingInformationService,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService,
    private dialog: MatDialog,

  ) { }

  ngOnInit(): void {
    this.subjectList$ = this.TestinforSV.getAll();
  }

  search(query){
    if(query) return this.subjectList$ = this.TestinforSV.search(`?${query}`);
    if(!query) return this.subjectList$ = this.TestinforSV.getAll();
  }

  edit(id){
    this.router.navigate(['create-exam-information/edit', id]);
  }

  close(id){
    this.swSV.confirmText('ต้องการปิดรอบสอบนี้ไหม').pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        return this.TestinforSV.checkandclosetest(id).pipe(
          tap(x => this.swSV.success('รอบสอบปิดแล้ว')),
          tap(x =>  this.subjectList$ = this.TestinforSV.getAll()),
          tap(x => this.cdr.detectChanges()),
          catchError(err => {
            this.swSV.errCloseExamDetailText(err.error);
            return throwError(err);
          })
        );
      })
    ).subscribe();
  }

  close2(id){
    const dialogRef = this.dialog.open(ConfirmRejectExamDialogComponent, {
      width: '550px',
      height: '250px',
      data: id,
      panelClass: 'custom-modalbox'
    });
    dialogRef.afterClosed().subscribe(result => {
      this.subjectList$ = this.TestinforSV.getAll();
    });
  }

}
