import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {Observable, throwError} from 'rxjs';
import {Router} from '@angular/router';
import {SubjectsService} from '../../../../core/service/settings/subjects.service';
import {TestingInformationService} from '../../../../core/service/testing-information/testing-information.service';
import {concatMap, filter, tap} from 'rxjs/operators';
import {SweetalertService} from '../../../../core/service/sweetalert/sweetalert';
import {ExcelAllTestService} from '../../../../core/service/report/excel-all-test/excel-all-test.service';

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

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

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

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

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

  export(id){
      this.reportExcelAllTestSV.get(id).subscribe(
          (res: any) => {
              // console.log(res)
              window.open(res);
          },
          err => {
              this.swSV.errText(err.error);
              return throwError(err);
          });
  }

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

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

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

  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.getAll()),
          tap(x => this.cdr.detectChanges())
        );
      })
    ).subscribe();
  }

}
