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 { FacultysService } from 'src/app/core/service/settings/facultys.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
  selector: 'app-faculty-dialog',
  templateUrl: './faculty-dialog.component.html',
  styleUrls: ['./faculty-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FacultyDialogComponent implements OnInit {
  form;
  statusMock = [{id:1, name:'ใช้งาน'},{id:2, name:'ยกเลิก'}]
  constructor(
    private fb: FormBuilder,
    private facultySV: FacultysService,
    private swSV: SweetalertService,
    private dialogRef: MatDialogRef<FacultyDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data
  ) {
    this.form = this.fb.group({
      status_id: 1,
      created_by: null,
      created_date: null,
      updated_by: null,
      updated_date: null,
      deleted_by: null,
      deleted_date: null,
      faculty_uid: null,
      faculty_code: null,
      faculty_name_th: null,
      faculty_name_en: null,
    })
   }

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

  save(){
    const form = this.form.getRawValue()
    if(this.data){
      this.facultySV.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.facultySV.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()
  }

}
