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 { AcademicYearService } from 'src/app/core/service/settings/academic-year.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { AcademicYearsDialogComponent } from '../../presenter/dialog/academic-years-dialog/academic-years-dialog.component';

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

  ngOnInit(): void {
    this.acdmYear$ = this.acdmYearSV.getAll()
  }

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

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

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

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

}
