import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {Observable, throwError} from 'rxjs';
import {MatDialog} from '@angular/material/dialog';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {BranchService} from '../../../../../core/service/settings/branch.service';
import {catchError, concatMap, filter, tap} from 'rxjs/operators';
import {TestcenterDialogComponent} from '../../presenter/dialog/testcenter-dialog/testcenter-dialog.component';

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

  constructor(
    private branchservice: BranchService,
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService
  ) { }

  ngOnInit(): void {
    this.branchsList$ = this.branchservice.getAll();
  }

  add(){
    const dialogRef = this.dialog.open(TestcenterDialogComponent, {
      width: '500px',
      // height: '600px',
    });
    dialogRef.afterClosed().pipe(
      tap(x => this.branchsList$ = this.branchservice.getAll()),
      tap(x => this.cdr.detectChanges())
    ).subscribe();
  }

  edit(id){
    const dialogRef = this.dialog.open(TestcenterDialogComponent, {
      width: '500px',
      // height: '600px',
      data: id
    });
    dialogRef.afterClosed().pipe(
      tap(x => this.branchsList$ = this.branchservice.getAll()),
      tap(x => this.cdr.detectChanges())
    ).subscribe();
  }

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

  search(query){
    // console.log(query);
    if(query) return this.branchsList$ = this.branchservice.search(`?${query}`);
    if(!query) return this.branchsList$ = this.branchservice.getAll();
  }

}
