import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {Observable, throwError} from 'rxjs';
import {TestingFieldService} from '../../../../../core/service/settings/testing-field.service';
import {MatDialog} from '@angular/material/dialog';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {TestingVdosService} from '../../../../../core/service/settings/testing-vdos.service';
import {catchError, concatMap, filter, tap} from 'rxjs/operators';
import {Router} from '@angular/router';

@Component({
    selector: 'app-testing-vdos',
    templateUrl: './testing-vdos.container.html',
    styleUrls: ['./testing-vdos.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestingVdosContainer implements OnInit {
    vdosList$ = new Observable();

    constructor(
        private router: Router,
        private testingVdosSV: TestingVdosService,
        private dialog: MatDialog,
        private cdr: ChangeDetectorRef,
        private swSV: SweetalertService
    ) { }

    ngOnInit(): void {
        this.vdosList$ = this.testingVdosSV.getAll();
    }

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

    add(){
        this.router.navigate(['testing-vdos/add']);
    }

    edit(id){
        this.router.navigate(['testing-vdos/edit', id]);
    }

    delete(id){
        this.swSV.confirm().pipe(
            filter(x => x.isConfirmed),
            concatMap(x => {
                return this.testingVdosSV.deleteData(id).pipe(
                    tap(x => this.swSV.removeSuccess()),
                    tap(x => this.vdosList$ = this.testingVdosSV.getAll()),
                    tap(x => this.cdr.detectChanges()),
                    catchError(err => {
                        console.log(err)
                        this.swSV.errText(err.error.description);
                        return throwError(err);
                    })
                );
            })
        ).subscribe();
    }

}
