import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {Observable} from 'rxjs';
import {BranchService} from '../../../../../core/service/settings/branch.service';
import {MatDialog} from '@angular/material/dialog';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {TestcenterDialogComponent} from '../../../testcenter/presenter/dialog/testcenter-dialog/testcenter-dialog.component';
import {concatMap, filter, tap} from 'rxjs/operators';
import {TestingFieldService} from '../../../../../core/service/settings/testing-field.service';
import {TestingFieldDialogComponent} from '../../presenter/dialog/testing-field-dialog/testing-field-dialog.component';

@Component({
    selector: 'app-testing-field',
    templateUrl: './testing-field.container.html',
    styleUrls: ['./testing-field.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestingFieldContainer implements OnInit {
    branchsList$ = new Observable();
    constructor(
        private testingfieldSV: TestingFieldService,
        private dialog: MatDialog,
        private cdr: ChangeDetectorRef,
        private swSV: SweetalertService
    ) { }

    ngOnInit(): void {
        this.branchsList$ = this.testingfieldSV.getAll();
    }

    add(){
        const dialogRef = this.dialog.open(TestingFieldDialogComponent, {
            width: '500px',
            // height: '460px',
        });
        dialogRef.afterClosed().pipe(
            tap(x => this.branchsList$ = this.testingfieldSV.getAll()),
            tap(x => this.cdr.detectChanges())
        ).subscribe();
    }

    edit(id){
        const dialogRef = this.dialog.open(TestingFieldDialogComponent, {
            width: '500px',
            // height: '460px',
            data: id
        });
        dialogRef.afterClosed().pipe(
            tap(x => this.branchsList$ = this.testingfieldSV.getAll()),
            tap(x => this.cdr.detectChanges())
        ).subscribe();
    }

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

    search(query){
        console.log(query);
        if(query) return this.branchsList$ = this.testingfieldSV.search(`?${query}`);
        if(!query) return this.branchsList$ = this.testingfieldSV.getAll();
    }

}
