import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { concatMap, filter, tap } from 'rxjs/operators';
import { FacultysService } from 'src/app/core/service/settings/facultys.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { FacultyDialogComponent } from '../../presenter/dialog/faculty-dialog/faculty-dialog.component';

@Component({
  selector: 'app-faculties',
  templateUrl: './faculties.container.html',
  styleUrls: ['./faculties.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FacultiesContainer implements OnInit {
  facultiesList$ = new Observable()
  constructor(
    private facultySV: FacultysService,
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService
  ) { }

  ngOnInit(): void {
    this.facultiesList$ = this.facultySV.getAll()
  }

  add(){
    const dialogRef = this.dialog.open(FacultyDialogComponent, {
      width: '500px',
      height: '300px',
    });
    dialogRef.afterClosed().pipe(
      tap(x => this.facultiesList$ = this.facultySV.getAll()),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
  }

  edit(id){
    const dialogRef = this.dialog.open(FacultyDialogComponent, {
      width: '500px',
      height: '300px',
      data: id
    });
    dialogRef.afterClosed().pipe(
      tap(x => this.facultiesList$ = this.facultySV.getAll()),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
  }

  delete(id){
    this.swSV.confirm().pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        return this.facultySV.deleteData(id).pipe(
          tap(x => this.swSV.removeSuccess()),
          tap(x => this.facultiesList$ = this.facultySV.getAll()),
          tap(x => this.cdr.detectChanges())
        )
      })
    ).subscribe()
  }

  search(query){
    if(query) return this.facultiesList$ = this.facultySV.search(`?${query}`)
    if(!query) return this.facultiesList$ = this.facultySV.getAll()
  }

}
