import { Component, OnInit, ChangeDetectionStrategy, Inject } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { AcademicYearService } from 'src/app/core/service/settings/academic-year.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
  selector: 'app-academic-years-dialog',
  templateUrl: './academic-years-dialog.component.html',
  styleUrls: ['./academic-years-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AcademicYearsDialogComponent implements OnInit {
  form;
  statusMock = [{id:1, name:'ใช้งาน'},{id:2, name:'ยกเลิก'}]
  constructor(
    private fb: FormBuilder,
    private swSV: SweetalertService,
    private dialogRef: MatDialogRef<AcademicYearsDialogComponent>,
    private acdmYearSV: AcademicYearService,
    @Inject(MAT_DIALOG_DATA) public data
  ) {
    this.form = this.fb.group({
      status_id: 1,
      created_by: null,
      created_datetime: null,
      updated_by: null,
      updated_datetime: null,
      deleted_by: null,
      deleted_datetime: null,
      academic_year_uid: null,
      academic_year_code: null,
      academic_year_name_th: null,
      academic_year_name_en: null
    })
   }

  ngOnInit(): void {
    if(this.data){
      this.acdmYearSV.get(this.data).pipe(
        tap(x => this.form.patchValue(x))
      ).subscribe()
    }
  }

  save(){
    const form = this.form.getRawValue()
    form.academic_year_name_en = form.academic_year_code
    form.academic_year_name_th = form.academic_year_code
    if(this.data){
      this.acdmYearSV.update2(form).pipe(
        tap(x => this.swSV.updateSuccess()),
        tap(x => this.dialogRef.close()),
        catchError(err => {
          this.swSV.err()
          this.dialogRef.close()
          return throwError(err)
        })
      ).subscribe()
    } else {
      this.acdmYearSV.add(form).pipe(
        tap(x => this.swSV.saveSuccess()),
        tap(x => this.dialogRef.close()),
        catchError(err => {
          this.swSV.err()
          this.dialogRef.close()
          return throwError(err)
        })
      ).subscribe()
    }
  }

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