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';

@Component({
  selector: 'app-create-exam-room',
  templateUrl: './create-exam-room.container.html',
  styleUrls: ['./create-exam-room.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CreateExamRoomContainer implements OnInit {
  subjectList$ = new Observable();

  constructor(
    private router: Router,
    private TestinforSV: TestingInformationService,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService
  ) { }

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

  add(){
    this.router.navigate(['create-exam-room/add']);
  }

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

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

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

  delete(id){
    this.swSV.confirm().pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        return this.TestinforSV.deleteData(id).pipe(
          tap(x => this.swSV.removeSuccess()),
          tap(x => this.subjectList$ = this.TestinforSV.getMaintrueANDOpenNull()),
          tap(x => this.cdr.detectChanges()),
          catchError(err => {
            this.swSV.errText(err.error);
            return throwError(err);
          })
        );
      })
    ).subscribe();
  }

}
