import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { EncService } from '../../../../services/enc.service';
import { MagnitudeDetailsResponse } from '../../../../interfaces/counters-activators.interface';
import { lastValueFrom } from 'rxjs';

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

  magnitudeControl: FormControl;
  magnitudeIDControl: FormControl;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _sysAdminService: SystemAdminService,
    private _encService: EncService,
  ) {
    this.isNew = true;
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.magnitudeControl = new FormControl('', [Validators.required, Validators.maxLength(50)]);
    this.magnitudeIDControl = new FormControl({value: '', disabled: true});
  }

  ngOnInit(): void {
    if(this._data.type == 'nuevo'){
      this.isNew = true;
      this.isLoading = false;
    }else{
      this.isNew = false;
      this.getMagnitude(this._data.idMagnitude);
    }
  }

  async getMagnitude(idMagnitudeEnc: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let magnitude: MagnitudeDetailsResponse = await lastValueFrom(this._sysAdminService.getMagnitude(idMagnitudeEnc, idUser, 1));

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

      if(!this.hasError){
        let idDec = await this._encService.decrypt(magnitude.response.ID_MAGNITUD);

        this.magnitudeIDControl.setValue(idDec);
        this.magnitudeControl.setValue(magnitude.response.MAGNITUD);
      }

      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;
    }
  }
}
