import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {Observable} 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 {concatMap, filter, tap} from 'rxjs/operators';

@Component({
  selector: 'app-change-exam-information',
  templateUrl: './change-exam-information.container.html',
  styleUrls: ['./change-exam-information.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChangeExamInformationContainer implements OnInit {
  Tab = 0;
  subjectList$ = new Observable();
  subjectListFalse$ = new Observable();
  constructor(
    private router: Router,
    private TestinforSV: TestingInformationService,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService
  ) { }

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

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

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

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

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

  search(query){
    if (this.Tab != 1){
      if(query) return this.subjectList$ = this.TestinforSV.search(`?${query}&is_main=true`);
      if(!query) return this.subjectList$ = this.TestinforSV.getMaintrue();
    }else {
      if(query) return this.subjectListFalse$ = this.TestinforSV.search(`?${query}&is_main=false`);
      if(!query) return this.subjectListFalse$ = this.TestinforSV.getMainfalse();
    }
  }

  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.getMaintrue()),
          tap(x => this.subjectListFalse$ = this.TestinforSV.getMainfalse()),
          tap(x => this.cdr.detectChanges())
        );
      })
    ).subscribe();
  }

  tab(index){
    this.Tab = index.index;
  }
}
