import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { InterventionService } from '../../../../services/personal-management/intervention.service';
import { SpecialtyDetails } from '../../../../interfaces/specialties.interface';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-specialty-form',
    templateUrl: './specialty-form.component.html',
    styleUrl: './specialty-form.component.css',
    standalone: false
})
export class SpecialtyFormComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  action: string;
  isNew: boolean;

  specialtyCodeControl: FormControl;
  specialtyNameControl: FormControl;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<SpecialtyFormComponent>,
    private _encService: EncService,
    private _interventionService: InterventionService,
  ){
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.action = '';
    this.isNew = true;

    this.specialtyCodeControl = new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(6)]);
    this.specialtyNameControl = new FormControl('', [Validators.required, Validators.maxLength(75)]);
  }

  ngOnInit(): void {
    this.isNew = this._data.type == 'new';
    this.action = this.isNew ? 'Registrar' : 'Editar';

    if(this.isNew){
      this.isLoading = false;
    }else{
      this.getSpecialty(this._data.specialty);
    }
  }

  async getSpecialty(code: string){
    try{
      let codeEnc = await this._encService.encrypt(code);
      let idUser = localStorage.getItem('idusuario')!;
      let specialty: SpecialtyDetails = await lastValueFrom(this._interventionService.getSpecialty(codeEnc, idUser, 1));

      this.hasError = specialty.error;
      this.errorStr = specialty.msg;

      if(!this.hasError){
        let codeDec = await this._encService.decrypt(specialty.response.CODIGO_ESPECIALIDAD);

        this.specialtyCodeControl.setValue(codeDec);
        this.specialtyCodeControl.disable();
        this.specialtyNameControl.setValue(specialty.response.NOMBRE_ESPECIALIDAD);
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }
      
      this.hasError = true;
      this.isLoading = false;
    }
  }

  validateCode(value: string){
    let valueUpper = value.toUpperCase();

    this.specialtyCodeControl.setValue(valueUpper);
    this.specialtyCodeControl.markAsTouched();
  }

  async closeForm(){
    let dataObj = {
      code: this.specialtyCodeControl.value,
      name: this.specialtyNameControl.value,
    }

    let dataStr = JSON.stringify(dataObj);
    let dataEnc = await this._encService.encrypt(dataStr);

    this._dialogRef.close(dataEnc);
  }
}
