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 { InsturctorPaymentAccoutService } from 'src/app/core/service/settingPayment/insturctor-payment-accout.service';
import { FacultysService } from 'src/app/core/service/settings/facultys.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
    selector: 'app-teacher-finance',
    templateUrl: './teacher-finance.container.html',
    styleUrls: ['./teacher-finance.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TeacherFinanceContainer implements OnInit {
    teacherList$ = new Observable()
    faculty$ = new Observable()
    constructor(
        private router: Router,
        private instructorPaymentSV: InsturctorPaymentAccoutService,
        private swSV: SweetalertService,
        private cdr: ChangeDetectorRef,
        private facultySV: FacultysService
    ) { }

    ngOnInit(): void {
        this.teacherList$ = this.instructorPaymentSV.getAll()
        this.faculty$ = this.facultySV.getAll()
    }

    add(){
        this.router.navigate(['setting-teacher-finance/add'])
    }

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

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

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

}
