import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {FacultysService} from '../../../../../core/service/settings/facultys.service';
import {MatDialog} from '@angular/material/dialog';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {SubjectTypesService} from '../../../../../core/service/settings/subject-types.service';
import {Observable} from 'rxjs';
import {FacultyDialogComponent} from '../../../faculties/presenter/dialog/faculty-dialog/faculty-dialog.component';
import {concatMap, filter, tap} from 'rxjs/operators';
import {TypesubjectDialogComponent} from "../../presenter/dialog/typesubject-dialog/typesubject-dialog.component";

@Component({
    selector: 'app-typesubject',
    templateUrl: './typesubject.container.html',
    styleUrls: ['./typesubject.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TypesubjectContainer implements OnInit {
    subjecttypeList$ = new Observable();
    constructor(
        private subjecttypeSV: SubjectTypesService,
        private dialog: MatDialog,
        private cdr: ChangeDetectorRef,
        private swSV: SweetalertService
    ) { }

    ngOnInit(): void {
        this.subjecttypeList$ = this.subjecttypeSV.getAll();
    }

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

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

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

    search(query){
        if(query) return this.subjecttypeList$ = this.subjecttypeSV.search(`?${query}`);
        if(!query) return this.subjecttypeList$ = this.subjecttypeSV.getAll();
    }

}
