import { TOUCH_BUFFER_MS } from '@angular/cdk/a11y';
import { formatDate } from '@angular/common';
import {Component, OnInit, ChangeDetectionStrategy, Inject, ChangeDetectorRef} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {catchError, combineAll, tap} from 'rxjs/operators';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { SyncService } from 'src/app/core/service/sync/sync.service';
import { TestingInformationService } from 'src/app/core/service/testing-information/testing-information.service';
import { createQueryStringFromObject } from 'src/app/shared/util/func';
import Swal from 'sweetalert2';
import {FormBuilder, FormGroup} from '@angular/forms';
import {data} from 'autoprefixer';
import { throwError } from 'rxjs';

@Component({
    selector: 'app-dialog-sync',
    templateUrl: './dialog-sync.component.html',
    styleUrls: ['./dialog-sync.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DialogSyncComponent    implements OnInit {
    form: FormGroup;
    isCanSync = false;
    isCanDetail;
    query = {
        from_date: null,
        testing_information_uid: null,
        to_date: null,
        is_delete: null
    };
    maxDate;
    testingInfomation;
    constructor(
        public dialogRef: MatDialogRef<DialogSyncComponent>,
        private syncSV: SyncService,
        private cdr: ChangeDetectorRef,
        private formBuilder: FormBuilder,
        private swSV: SweetalertService,
        private testingInformationSV: TestingInformationService,
        @Inject(MAT_DIALOG_DATA) public data
    ) {
        this.form = this.formBuilder.group({
            testing_information_uid: null,
            is_delete: true,
        });
    }

    ngOnInit(): void {
        this.maxDate = new Date();
        this.testingInformationSV.getMaintrueAndTestInforUid(this.data.testing_information_uid).pipe(
            tap(x => this.testingInfomation = x),
            tap(x => this.form.get('testing_information_uid').patchValue(this.data.testing_information_uid)),
            tap(x => this.cdr.detectChanges()),
        ).subscribe();
        this.testingInformationSV.checkBeforeSync(this.data.testing_information_uid).pipe(
            tap(y => this.isCanSync = true),
            tap(y => this.cdr.detectChanges()),
            catchError(err => {
                this.isCanDetail = err.error;
                this.cdr.detectChanges()
                return throwError(err);
            })
        ).subscribe()
    }

    save(){
        this.query.from_date = formatDate(this.query.from_date, 'yyyy-MM-dd', 'en-US');
        this.query.to_date = formatDate(this.query.to_date, 'yyyy-MM-dd', 'en-US');
        this.query.is_delete = this.form.get('is_delete').value;
        const query = createQueryStringFromObject(this.query);
        Swal.fire({
            title: 'กำลังสร้างข้อสอบ...',
            // text: `ใช้เวลาประมาณ ${this.data.mins} / นาที`,
            html: `ใช้เวลาประมาณ ${this.data.mins} นาที`,
            allowEscapeKey: false,
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading(Swal.getDenyButton())
            }
        });
        this.syncSV.sync_all(`?${query}`).pipe(
            tap(x => Swal.hideLoading()),
            tap(x => Swal.close()),
            tap((x:any) => this.swSV.saveSuccessCustom('เสร็จสิ้น',x)),
            tap(x => this.dialogRef.close()),
            catchError(err => {
                Swal.hideLoading()
                Swal.close()
                this.swSV.errText(err.error)
                return throwError(err)
            })
        ).subscribe();
    }

    cancel(){
        this.dialogRef.close()
    }

    setDate(x){
        const selectData = this.testingInfomation.filter((member) => {
            return member.testing_information_uid === x;
        });
        if (selectData !== undefined){
            this.query.from_date = selectData[0].testing_start_datetime;
            this.query.to_date = selectData[0].testing_end_datetime;
            this.query.testing_information_uid = selectData[0].testing_information_uid;
        }else {
            this.swSV.error('ไม่พบข้อมูล');
        }
    }

    display(uid){
        if (uid && this.testingInfomation) return this.testingInfomation.find(x => x.testing_information_uid === uid)?.testing_information_name
    }

}
