import { Location } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, Inject, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { BaseForm } from 'src/app/core/base/base-form';
import { StudentService } from 'src/app/core/service/student/student.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { TestingInformationService } from 'src/app/core/service/testing-information/testing-information.service';

@Component({
  selector: 'app-student-dialog',
  templateUrl: './student-dialog.component.html',
  styleUrls: ['./student-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class StudentDialogComponent extends BaseForm implements OnInit {
  subject;
  constructor(
    public dialog: MatDialog,
    public dialogRef: MatDialogRef<StudentDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    public fb: FormBuilder,
    public activeRoute: ActivatedRoute,
    public location: Location,
    public router: Router,
    private testingInformationSV: TestingInformationService,
    private studentSV: StudentService,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService
  ) {
    super(router,activeRoute,fb,location)
   }

  ngOnInit(): void {
    this.testingInformationSV.get(this.data.params_data.testing_information_uid).pipe(
      tap(x => this.subject = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
  }

  createForm(): FormGroup {
    return this.fb.group({
      testing_information_uid: null,
      branch_uid: null,
      testing_field_uid: null,
      testing_center_uid: null,
      testing_date: null,
      section: null,
      student_code: [null,Validators.required],
      student_name_th: [null,Validators.required],
      student_name_en: null,
      register_subject_code: [null,Validators.required]
    })
  }

  confirm(){
    // this.dialogRef.close()
    this.form.patchValue(this.data.params_data)
    const form = this.form.getRawValue()
    form.section = +form.section
    const isDuplicate = this.data.student_list.find(x => x.student_code == form.student_code)
    if(isDuplicate){
      this.swSV.errText('รหัสนักศึกษาซ้ำกัน')
    }else{
      this.studentSV.addStudent(form).pipe(
        tap(x => this.swSV.saveSuccess()),
        tap(x => this.dialogRef.close()),
        catchError(err => {
          this.swSV.err()
          return throwError(err)
        })
      ).subscribe()
    }

  }

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