import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { tap, filter, concatMap } from 'rxjs/operators';
import { AcademicSemesterService } from 'src/app/core/service/settings/academic-semester.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { AcademicSemestersDialogComponent } from '../../presenter/dialog/academic-semesters-dialog/academic-semesters-dialog.component';

@Component({
  selector: 'app-academic-semesters',
  templateUrl: './academic-semesters.container.html',
  styleUrls: ['./academic-semesters.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AcademicSemestersContainer implements OnInit {
  acdmSem$ = new Observable()
  constructor(
    private acdmSemSV: AcademicSemesterService,
    private cdr: ChangeDetectorRef,
    private dialog: MatDialog,
    private swSV: SweetalertService
  ) { }

  ngOnInit(): void {
    this.acdmSem$ = this.acdmSemSV.getAll()
  }

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

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

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

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

}
