import { Component, Inject, OnInit } from '@angular/core';
import { SecurityManagementAssociatedOrders, SecurityManagementDetailsResponse, SecurityManagementListItem } from '../../../../interfaces/corrective-maintenance.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { EncService } from '../../../../services/enc.service';
import { lastValueFrom } from 'rxjs';

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

  securityManagement: SecurityManagementListItem | null;

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

    this.securityManagement = null;
  }

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

  async getSecurityManagement(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let securityManagement: SecurityManagementDetailsResponse = await lastValueFrom(this._correctiveMaintenanceService.getSecurityManagement(
        this._data.idSecManage,
        idUser,
        1
      ));

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

      if(!this.hasError){
        securityManagement.response.ID_GERENCIA_SEGURIDAD = await this._encService.decrypt(securityManagement.response.ID_GERENCIA_SEGURIDAD);
        let workOrders: SecurityManagementAssociatedOrders[] = [];
        
        for(const order of securityManagement.response.ORDENES_TRABAJO!){
          order.ID_ORDEN = await this._encService.decrypt(order.ID_ORDEN);
          workOrders.push(order);
        }

        securityManagement.response.ORDENES_TRABAJO = workOrders;
        this.securityManagement = securityManagement.response;
      }

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