import {Component, OnInit, ChangeDetectionStrategy, Inject} from '@angular/core';
import {FormBuilder} from '@angular/forms';
import {CalendarTypeService} from '../../../../../../core/service/settings/calendar-type.service';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {catchError, tap} from 'rxjs/operators';
import {DepartmentService} from '../../../../../../core/service/settings/department.service';
import {throwError} from 'rxjs';
import {FacultysService} from '../../../../../../core/service/settings/facultys.service';

@Component({
  selector: 'app-department-dialog',
  templateUrl: './department-dialog.component.html',
  styleUrls: ['./department-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DepartmentDialogComponent implements OnInit  {
  faculty = [];
  form;
  statusMock = [{id:1, name:'ใช้งาน'},{id:2, name:'ยกเลิก'}]
  private curSub: any;
  constructor(
    private fb: FormBuilder,
    private facultySV: FacultysService,
    private swSV: SweetalertService,
    private dialogRef: MatDialogRef<DepartmentDialogComponent>,
    private departmentSV: DepartmentService,

    @Inject(MAT_DIALOG_DATA) public data
  ) {
    this.form = this.fb.group({
      status_id: 1,
      create_by: null,
      create_date: null,
      updated_by: null,
      updated_date: null,
      deleted_by: null,
      deleted_date: null,
      faculty_uid: null,
      department_uid: null,
      department_code: null,
      department_name_th: null,
      department_name_en: null
    });
  }

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

  save(){
    const form = this.form.getRawValue();
    if(this.data){
      this.departmentSV.update2(form).pipe(
        tap(x => this.swSV.updateSuccess()),
        tap(x => this.dialogRef.close()),
        catchError(err => {
          this.swSV.err()
          this.dialogRef.close('err');
          return throwError(err)
        })
      ).subscribe()
    } else {
      this.departmentSV.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()
  }

  displayFacultyname(uid){
    if (uid && this.faculty) return this.faculty.find(x => x.faculty_uid === uid)?.faculty_name_th
    if (uid && !this.faculty) return this.curSub?.faculty_name_th
  }

}
