import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {MatDialog} from '@angular/material/dialog';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {Observable} from 'rxjs';
import {EducationTypesService} from '../../../../../core/service/settings/education-types.service';
import {AcademicYearsDialogComponent} from '../../../academic-years/presenter/dialog/academic-years-dialog/academic-years-dialog.component';
import {concatMap, filter, tap} from 'rxjs/operators';
import {EducationTypeDialogComponent} from '../../presenter/dialog/education-type-dialog/education-type-dialog.component';

@Component({
    selector: 'app-education-type',
    templateUrl: './education-type.container.html',
    styleUrls: ['./education-type.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class EducationTypeContainer implements OnInit {
    eductypeList$ = new Observable();
    constructor(
        private    eductypeSV: EducationTypesService,
        private cdr: ChangeDetectorRef,
        private dialog: MatDialog,
        private swSV: SweetalertService
    ) { }

    ngOnInit(): void {
        this.eductypeList$ = this.eductypeSV.getAll();
    }
    add(){
        const dialogRef = this.dialog.open(EducationTypeDialogComponent, {
            width: '500px',
            height: '300px',
        });
        dialogRef.afterClosed().pipe(
            tap(x => this.eductypeList$ = this.eductypeSV.getAll()),
            tap(x => this.cdr.detectChanges())
        ).subscribe();
    }

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

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

    search(query){
        // console.log(query)
        if(query) return this.eductypeList$ = this.eductypeSV.search(`?${query}`);
        if(!query) return this.eductypeList$ = this.eductypeSV.getAll();
    }

}
