import {catchError, tap, filter, concatMap} from 'rxjs/operators';
import {Component, OnInit, ChangeDetectionStrategy, Inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {TestingInformationService} from '../../../../../core/service/testing-information/testing-information.service';
import { throwError } from 'rxjs';
import {formatDate} from '@angular/common';

@Component({
  selector: 'app-approve-dialog',
  templateUrl: './approve-dialog.component.html',
  styleUrls: ['./approve-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ApproveDialogComponent implements OnInit {
    RoomChoose = '';
    today = new Date();
    dateSelect = null;
    Roomdata = [];
    Roomsend = {
        testing_information_uid: null,
        period_id: null,
        date: null
    };
    constructor(
        private testingInforSV: TestingInformationService,
        private swSV: SweetalertService,
        private dialogRef: MatDialogRef<ApproveDialogComponent>,
        @Inject(MAT_DIALOG_DATA) public data
    ) { }

    ngOnInit(): void {
        this.Roomdata = this.data.data.testing_periods
    }

    chooseRoom(testing_center_uid , branchNameTH){
        if (this.RoomChoose !== testing_center_uid){
            this.RoomChoose = testing_center_uid;
        }else{
            this.RoomChoose = '';
        }
    }

    choosePeriod(testing_center_uid , period_id){
        if (this.RoomChoose !== period_id){
            this.RoomChoose = period_id;
        }else{
            this.RoomChoose = '';
        }
    }

    confirm(){
        if (this.Roomsend.date === null){
            return this.swSV.error('กรุณากรอกวันที่ต้องการปล่อยสอบ');
        }
        const Roomsend = this.Roomdata.filter((x) => {
            return x.period_id === this.RoomChoose;
        });
        this.Roomsend.period_id = Roomsend[0].period_id;
        this.Roomsend.testing_information_uid = Roomsend[0].testing_information_uid;
        this.Roomsend.date = formatDate(this.Roomsend.date, 'yyyy-MM-dd', 'en-US');
        this.testingInforSV.approveExam(this.Roomsend.testing_information_uid, this.Roomsend.period_id, this.Roomsend.date).pipe(
            tap(x => {
                this.testingInforSV.approveExamAPIstore(this.Roomsend.testing_information_uid, this.Roomsend.period_id, this.Roomsend.date).subscribe();
            }),
            tap(x => this.swSV.success('อนุมัติข้อสอบสำเร็จ')),
            tap(x => this.dialogRef.close()),
            catchError(err => {
                this.swSV.err();
                return throwError(err);
            })
        ).subscribe();
    }

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