import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { MySettingAssessmentModel, SettingAssessmentModel } from 'src/app/shared/model/setting-assessment.model';
import { SettingAssessmentService } from 'src/app/shared/services/setting-assessment.service';

@Component({
  selector: 'app-competency-configuration',
  templateUrl: './competency-configuration.component.html',
  styleUrls: ['./competency-configuration.component.scss']
})
export class CompetencyConfigurationComponent {
  setting: { loading: boolean, data: SettingAssessmentModel } = { loading: false, data: new MySettingAssessmentModel() }
  currentDate = new Date()
  yearList = [
    (this.currentDate.getFullYear() - 1) + "",
    (this.currentDate.getFullYear()) + "",
    (this.currentDate.getFullYear() + 1) + ""
  ]
  constructor(private settingAssessmentService: SettingAssessmentService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef
  ) { }
  ngOnInit(): void {
    this.getSettingList()
  }
  getSettingList() {
    this.setting.loading = true
    this.settingAssessmentService.get().subscribe({
      next: response => {
        this.setting.data = new MySettingAssessmentModel(response)
        this.setting.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.setting.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  saveSetting() {
    this.setting.loading = true
    this.settingAssessmentService.post(new MySettingAssessmentModel({ ...this.setting.data, expectationLevel: +(this.setting.data.expectationLevel), active: true })).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getSettingList()
        } else {
          this.showAlert(response.message, 'error')
          this.setting.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.setting.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    })
  }

  checkEmpty(data?: string | number) {
    switch (typeof data) {
      case ('number'): {
        return data == null || data == undefined
      }
      case ('string'): {
        return data == "" || data == null || data == undefined
      }
      default: {
        return true
      }
    }
  }
}

