import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError, filter, switchMap, tap } from 'rxjs/operators';
import { invigilatorCostService } from 'src/app/core/service/settingPayment/invigilator-cost.service';
import { AcademicSemesterService } from 'src/app/core/service/settings/academic-semester.service';
import { AcademicYearService } from 'src/app/core/service/settings/academic-year.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
    selector: 'app-invigilate-finance',
    templateUrl: './invigilate-finance.container.html',
    styleUrls: ['./invigilate-finance.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class InvigilateFinanceContainer implements OnInit {
    invigilateList$ = new Observable()
    acdmSem$ = new Observable()
    acdmYear$ = new Observable()
    constructor(
        private router: Router,
        private invCostSV: invigilatorCostService,
        private acdmSemSV: AcademicSemesterService,
        private acdmYearSV: AcademicYearService,
        private swSV: SweetalertService,
        private cdr: ChangeDetectorRef
    ) { }

    ngOnInit(): void {
        this.invigilateList$ = this.invCostSV.getAll()
        this.acdmSem$ = this.acdmSemSV.getAll()
        this.acdmYear$ = this.acdmYearSV.getAll()
    }

    edit(id){
        this.router.navigate(['/setting-invigilate-finance/edit',id])
    }

    delete(uid){
        this.swSV.confirm().pipe(
            filter(x => x.isConfirmed),
            switchMap(x => {
                return this.invCostSV.deleteData(uid).pipe(
                    tap(x => this.swSV.removeSuccess()),
                    tap(x => this.invigilateList$ = this.invCostSV.getAll()),
                    tap(x => this.cdr.detectChanges()),
                    catchError(err => {
                        this.swSV.errText(err.error)
                        return throwError(err)
                    })
                )
            })
        ).subscribe()
    }

}
