import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { IdpDevelopmentModel, MyIdpDevelopmentModel } from 'src/app/shared/model/idp-development.model';
import { IdpDevelopmentService } from 'src/app/shared/services/idp-development.service';

@Component({
  selector: 'app-set-idp-development-plan',
  templateUrl: './set-idp-development-plan.component.html',
  styleUrls: ['./set-idp-development-plan.component.scss']
})
export class SetIdpDevelopmentPlanComponent {
  idpLoading = false
  idpData: IdpDevelopmentModel = new MyIdpDevelopmentModel({})
  constructor(private idpDevelopmentService: IdpDevelopmentService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit(): void {
    this.getIdpData()
  }

  getIdpData() {
    this.idpLoading = true
    this.idpDevelopmentService.getList().subscribe({
      next: response => {
        this.idpData = new MyIdpDevelopmentModel(response)
        this.idpData.developmentPlan.sort((a, b) => +a.planId - +b.planId)
        this.idpLoading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.idpLoading = false
        this.cdr.detectChanges()
      }
    })
  }

  saveIdp() {
    this.idpDevelopmentService.post(this.idpData).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getIdpData()
        } else {
          this.showAlert(response.message, 'error')
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
      }
    })
  }

  showSuccess() {
    this.toastr.success('บันทึกข้อมูลสำเร็จ', 'เเจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    });
  }

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