import { Component, Inject, OnInit } from '@angular/core';
import { MaintenancePlanDetails, MaintenancePlanDetailsResponse } from '../../../../interfaces/corrective-maintenance.interface';
import { PriorityInterface } from '../../../system-admin/system-params/system-params.component';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { EncService } from '../../../../services/enc.service';
import { FunctionsService } from '../../../../services/functions.service';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { lastValueFrom } from 'rxjs';
import { TempFileInfo } from '../../../../interfaces/temp-file-info.interface';

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

  maintenancePlan: MaintenancePlanDetails | null;
  priorities: PriorityInterface[];

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

    this.maintenancePlan = null;
    this.priorities = [];
  }

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

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

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        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.priorities = prioritiesArr;
        this.getMaintenancePlanDetails();
      }
    }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;
    }
  }

  async getMaintenancePlanDetails(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let maintenancePlan: MaintenancePlanDetailsResponse = await lastValueFrom(this._correctiveMaintenanceService.getMaintenancePlan(
        this._data.idPlan,
        idUser,
        1
      ));

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

      if(!this.hasError){
        maintenancePlan.response.ID_PLAN = await this._encService.decrypt(maintenancePlan.response.ID_PLAN);
        maintenancePlan.response.EQUIPAMIENTO = await this._encService.decrypt(maintenancePlan.response.EQUIPAMIENTO);

        if(maintenancePlan.response.LRU != null){
          maintenancePlan.response.LRU = await this._encService.decrypt(maintenancePlan.response.LRU);
        }

        maintenancePlan.response.ESTADO_FUNCIONAMIENTO_EQUIPAMIENTO = this.getFunctionStatus(maintenancePlan.response.ESTADO_FUNCIONAMIENTO_EQUIPAMIENTO);

        if(maintenancePlan.response.ESTADO_FUNCIONAMIENTO_LRU != null){
          maintenancePlan.response.ESTADO_FUNCIONAMIENTO_LRU = this.getFunctionStatus(maintenancePlan.response.ESTADO_FUNCIONAMIENTO_LRU);
        }

        let specialtiesArr = JSON.parse(maintenancePlan.response.ESPECIALIDADES_REQUERIDAS);
        let specialtiesObj = JSON.parse(maintenancePlan.response.CONFIGURACION_OPERARIOS);
        let specialtiesConf: any[] = [];

        let planPriorityDec = await this._encService.decrypt(maintenancePlan.response.PRIORIDAD);
        for(const priority of this.priorities){
          let valueDec = await this._encService.decrypt(priority.value);
          if(planPriorityDec == valueDec){
            maintenancePlan.response.PRIORIDAD_OBJ = priority;
          }
        }

        for(const specialty of specialtiesArr){
          let specialtyStaff = specialtiesObj[specialty];
          specialtiesConf.push({
            specialty: specialty,
            config: specialtyStaff
          });
        }

        let documentsArr: TempFileInfo[] = JSON.parse(maintenancePlan.response.DOCUMENTOS_RELACIONADOS);
        let documentsFn: TempFileInfo[] = [];

        for(const file of documentsArr){
          file.size = this._functionsService.formatBytes(parseInt(file.size));
          documentsFn.push(file);
        }

        maintenancePlan.response.ESPECIALIDADES_REQUERIDAS_CONF = specialtiesConf;
        maintenancePlan.response.DOCUMENTOS_RELACIONADOS_ARR = documentsFn;
        maintenancePlan.response.FECREG = this._functionsService.orderDate(maintenancePlan.response.FECREG);

        if(maintenancePlan.response.FECMOD != null){
          maintenancePlan.response.FECMOD = this._functionsService.orderDate(maintenancePlan.response.FECMOD);
        }

        maintenancePlan.response.ACTIVADOR = await this._encService.decrypt(maintenancePlan.response.ACTIVADOR);
        maintenancePlan.response.CONTADOR = await this._encService.decrypt(maintenancePlan.response.CONTADOR);
        maintenancePlan.response.PRIORIDAD = await this._encService.decrypt(maintenancePlan.response.PRIORIDAD);
        maintenancePlan.response.SCADA = await this._encService.decrypt(maintenancePlan.response.SCADA);
        maintenancePlan.response.SINTOMA = await this._encService.decrypt(maintenancePlan.response.SINTOMA);
        
        this.maintenancePlan = maintenancePlan.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 = 'Ocurrió un error inesperado.';
      }

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

  getFunctionStatus(status: string): string{
    if(status == 'EF'){
      return 'En funcionamiento';
    }else if(status == 'DE'){
      return 'Detenido';
    }else if(status == 'DP'){
      return 'Detenido parcialmente';
    }else{
      return '-';
    }
  }
}
