import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, Inject} from '@angular/core';
import {BaseForm} from '../../../../../../core/base/base-form';
import {FormBuilder, Validators} from '@angular/forms';
import {SubjectTypesService} from '../../../../../../core/service/settings/subject-types.service';
import {SubjectsService} from '../../../../../../core/service/settings/subjects.service';
import {EducationTypesService} from '../../../../../../core/service/settings/education-types.service';
import {FacultysService} from '../../../../../../core/service/settings/facultys.service';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {UploadService} from '../../../../../../core/service/upload/upload.service';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {ExamResultSubjectService} from '../../../../../../core/service/report/exam-result-subject/exam-result-subject.service';
import {ExamNotificationService} from '../../../../../../core/service/testing-information/exam-notification.service';
import {catchError, concatMap, tap} from 'rxjs/operators';
import {throwError} from 'rxjs';

@Component({
  selector: 'app-notification-check-exam-dialog',
  templateUrl: './notification-check-exam-dialog.component.html',
  styleUrls: ['./notification-check-exam-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class NotificationCheckExamDialogComponent extends BaseForm implements OnInit {
  text = ''
  emailList: any = [];
  constructor(
    public fb: FormBuilder,
    public router: Router,
    public activeRoute: ActivatedRoute,
    private swSV: SweetalertService,
    public location: Location,
    private examResultSV: ExamNotificationService,
    private dialogRef: MatDialogRef<NotificationCheckExamDialogComponent>,
    private examNotiSV: ExamNotificationService,
    @Inject(MAT_DIALOG_DATA) public data,
    private cdr: ChangeDetectorRef
  ) {
    super(
      router,
      activeRoute,
      fb,
      location
    );
    this.form = this.fb.group({
      topic: 'ตรวจข้อสอบ e-Testing',
      body: null,
      email: null,
    });
  }

  ngOnInit(): void {
    this.examNotiSV.getInstructorEmail(this.data.subject_uid).pipe(
      tap(x => this.emailList = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
    let date = new Date(this.data.testing_datetime).toLocaleDateString('th-TH',{
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    })
    this.text = `วิชา : ${this.data.subject_name}<br>วันที่สอบ: ${date}<br>รอการตรวจข้อสอบ : ${this.data.count_waiting}`
    this.form.get('body').setValue(this.text)
  }

  save(){
    const form = this.form.getRawValue();
    this.swSV.loadingStart()
    this.examResultSV.getSendUpdateNotiDate(this.data).pipe(
      catchError(err => {
        this.swSV.close()
        this.swSV.err()
        return throwError(err)
      }),
      concatMap(x => {
        return this.examResultSV.sendMail(form).pipe(
          tap(x => this.swSV.close()),
          tap(x => this.swSV.saveSuccess('ส่งอีเมล์สำเร็จ')),
          tap(x => this.dialogRef.close()),
          catchError(err => {
            this.swSV.close()
            this.swSV.err()
            return throwError(err)
          })
        )
      })
    ).subscribe()
    // this.examResultSV.getSendUpdateNotiDate(
    //   this.data.testing_information_uid,
    //   this.data.subject_uid,
    //   this.data.testing_datetime,
    //   this.data.period_id).pipe(
    //   catchError(err => {
    //     this.swSV.err();
    //     return throwError(err);
    //   })
    // ).subscribe(
    //   result => {
    //     this.examResultSV.sendMail(form).pipe(
    //       tap(x => this.swSV.saveSuccess('ส่งอีเมล์สำเร็จ')),
    //       catchError(err => {
    //         this.swSV.err();
    //         return throwError(err);
    //       })
    //     ).subscribe();
    //   }
    // );
  }

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

}
