import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {Observable} from 'rxjs';
import {MatDialog} from '@angular/material/dialog';
import {CalendarTypeService} from '../../../../../core/service/settings/calendar-type.service';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {DepartmentService} from '../../../../../core/service/settings/department.service';
import {CalendarDialogComponent} from '../../../calendars/presenter/dialog/calendar-dialog/calendar-dialog.component';
import {concatMap, filter, tap} from 'rxjs/operators';
import {DepartmentDialogComponent} from '../../presenter/dialog/department-dialog/department-dialog.component';

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

  constructor(
    private dialog: MatDialog,
    private departmentSV: DepartmentService,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService
  ) { }

  ngOnInit(): void {
    this.departmentList$ = this.departmentSV.getAll()
  }

  add(){
    const dialogRef = this.dialog.open(DepartmentDialogComponent, {
      width: '500px',
      height: '455px',
      autoFocus: false
    });
    dialogRef.afterClosed().pipe(
      tap(x => this.departmentList$ = this.departmentSV.getAll()),
      tap(x => this.cdr.detectChanges())
    ).subscribe();
  }

  edit(id){
    const dialogRef = this.dialog.open(DepartmentDialogComponent, {
      width: '500px',
      height: '455px',
      autoFocus: false,
      data: id
    });
    dialogRef.afterClosed().pipe(
      tap(x => this.departmentList$ = this.departmentSV.getAll()),
      tap(x => this.cdr.detectChanges())
    ).subscribe();
  }

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

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

}
