import {MatDialog} from '@angular/material/dialog';
import {TestingCenterService} from './../../../../../core/service/TestingCenter/testing-center.service';
import {VEligibleCandidatesService} from './../../../../../core/service/testing-register/v-eligible-candidates.service';
import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, OnChanges, SimpleChanges} from '@angular/core';
import {Observable, throwError} from 'rxjs';
import {ActivatedRoute, Router} from '@angular/router';
import {SubjectsService} from 'src/app/core/service/settings/subjects.service';
import {BranchService} from 'src/app/core/service/settings/branch.service';
import {TestingFieldService} from 'src/app/core/service/settings/testing-field.service';
import {DialogSyncComponent} from '../../../candidate-list/presenter/dialog/dialog-sync/dialog-sync.component';
import {catchError, concatMap, filter, map, switchMap, tap} from 'rxjs/operators';
import {SyncService} from "../../../../../core/service/sync/sync.service";
import Swal from "sweetalert2";
import {SweetalertService} from "../../../../../core/service/sweetalert/sweetalert";
import {TestingInformationService} from 'src/app/core/service/testing-information/testing-information.service';
import {CustomeEventPage} from 'src/app/core/base/base-list';

@Component({
    selector: 'app-check-candidate-list',
    templateUrl: './check-candidate-list.container.html',
    styleUrls: ['./check-candidate-list.container.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class CheckCandidateListContainer implements OnInit {
    testingInformationUID;
    eligibleCandidate$ = new Observable();
    subject$ = new Observable()
    testingField$ = new Observable()
    testingCenter$ = new Observable()
    branch$ = new Observable()
    haveExam: false;
    testingInfoData;
    paginator;
    currentQueryPaging = '';
    currentQueryString = '';

    constructor(
        public activeRouter: ActivatedRoute,
        private VECandidateSV: VEligibleCandidatesService,
        private subjectSV: SubjectsService,
        private syncSV: SyncService,
        private swSV: SweetalertService,
        private dialog: MatDialog,
        private testingInfoSV: TestingInformationService
    ) {
    }

    ngOnInit(): void {
        this.activeRouter.params.pipe(
            tap(x => this.testingInformationUID = x.id),
            tap(x => this.currentQueryString = `testing_information_uid=${x.id}`),
            concatMap(x => this.testingInfoSV.get(this.testingInformationUID)),
            tap(x => this.testingInfoData = x)
        ).subscribe()
        this.subject$ = this.subjectSV.getAll()
    }

    pageChange(event: CustomeEventPage) {
        this.paginator = event.paginator
        this.currentQueryPaging = event.queryStringPage
        if (this.currentQueryString) {
            return this.eligibleCandidate$ = this.VECandidateSV.getPage(`${event.queryStringPage}?${this.currentQueryString}`)
        } else {
            return this.eligibleCandidate$ = this.VECandidateSV.getPage(`${event.queryStringPage}`)
        }
    }

    search(queryString) {
        console.log(queryString);
        this.currentQueryString = queryString;
        if (queryString) {
            this.paginator.firstPage();
            this.eligibleCandidate$ = this.VECandidateSV.getPage(`${this.currentQueryPaging}?${this.currentQueryString}`);
            // if (haveExan !== false) {
            //     this.paginator.firstPage();
            //     this.eligibleCandidate$ = this.VECandidateSV.getPage(`${this.currentQueryPaging}?${this.currentQueryString}`)
            //         .pipe(map((x: any) => {
            //             const res = x.results.filter(y => y.have_exan === haveExan);
            //             return {...x, results: [...res], row_count: x.row_count};
            //         }));
            //     return this.eligibleCandidate$;
            // } else {
            //     return this.eligibleCandidate$ = this.VECandidateSV.getPage(`${this.currentQueryPaging}`)
            // }
        }
        if (!queryString) {
            return this.eligibleCandidate$ = this.VECandidateSV.getPage(`${this.currentQueryPaging}`)
        }
    }

    syncData(data) {
        const dataObject = {
            testing_information_uid: this.testingInformationUID,
            mins: (this.paginator.length * 3) / 60
        }
        const dialogRef = this.dialog.open(DialogSyncComponent, {
            width: '500px',
            height: '340px',
            data: dataObject,
        });
    }

    clearData(data) {
        this.swSV.confirmText('ต้องการล้างการสร้างข้อสอบหรือไม่').pipe(
            filter(x => x.isConfirmed),
            concatMap(x => {
                Swal.fire({
                    title: 'กำลังซิงค์ข้อมูล...',
                    html: 'กรุณารอ...',
                    allowEscapeKey: false,
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                return this.syncSV.deleteTestInforUid(this.testingInformationUID).pipe(
                    tap(x => Swal.hideLoading()),
                    tap(x => Swal.close()),
                    tap(x => this.swSV.success('เสร็จสิ้น')),
                    catchError(err => {
                        this.swSV.errOpenExamDetailText(err.error);
                        return throwError(err);
                    })
                );
            })
        ).subscribe();
    }


}
