import { Component, OnInit } from '@angular/core';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { FormControl, Validators } from '@angular/forms';
import { EncService } from '../../../services/enc.service';
import { SystemAdminService } from '../../../services/system-admin.service';
import { MatDialogRef } from '@angular/material/dialog';
import { ResourcesService } from '../../../services/resources.service';
import { lastValueFrom } from 'rxjs';

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

  orderPriorities: PriorityInterface[];
  priorityControl = new FormControl('', Validators.required);

  constructor(
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _dialogRef: MatDialogRef<CriticalityManagementComponent>,
    private _resourcesService: ResourcesService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.orderPriorities = [];
  }

  ngOnInit(): void {
    this.getPriorities();
  }

  async getPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._sysAdminService.getOrderPriorities(idUser, 1));

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

      if(!this.hasError){
        let prioritiesArr: PriorityInterface[] = [];
        for(const priority of priorities.response.order_priorities as PriorityInterface[]){
          let valueEnc = await this._encService.encrypt(priority.value);

          priority.label = `${priority.label} (${priority.value})`;
          priority.value = valueEnc;

          prioritiesArr.push(priority);
        }

        this.orderPriorities = prioritiesArr;
      }

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

      this.hasError = true;
      this.isLoading = false;
    }
  }

  saveCriticality(value: string | null){
    if(value != null){
      this._dialogRef.close(value);
    }else{
      this._resourcesService.openSnackBar('El valor de la criticidad seleccionado es inválido.');
    }
  }
}
