import { Component, Inject, OnInit } from '@angular/core';
import { EquipmentDetails, EquipmentDetailsResponse } from '../../../../interfaces/equipment-management.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { EquipmentManagementService } from '../../../../services/equipment-management.service';
import { lastValueFrom } from 'rxjs';
import { SocketService } from '../../../../services/socket.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { ResourcesService } from '../../../../services/resources.service';
import { Router } from '@angular/router';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { FunctionsService } from '../../../../services/functions.service';
import { Permissions } from '../../../../interfaces/permissions.interface';
import { GdelService } from '../../../../services/gdel.service';
import { DOCUMENT } from '@angular/common';

const ID_MODULE = "S002V01M07GEEQ";
@Component({
    selector: 'app-equipment-details-dialog',
    templateUrl: './equipment-details-dialog.component.html',
    styleUrl: './equipment-details-dialog.component.css',
    standalone: false
})
export class EquipmentDetailsDialogComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  equipment: EquipmentDetails | null;
  
  equipmentDetailsEnabled: boolean;
  relatedDocumentsTableEnabled: boolean;
  equipmentImagesGalleryEnabled: boolean;
  securityCriticalityEnabled: boolean;

  codeTypes = {
    1: "General",
    2: "PCC",
    3: "Origen y destino para líneas y enlaces",
    4: "Origen y destino para estaciones y edificios",
    5: "Tren",
    6: "Origen y destino mixto",
    7: "Almacén"
  };

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    @Inject(DOCUMENT) private _document: Document,
    private _encService: EncService,
    private _equipmentManagementService: EquipmentManagementService,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService,
    private _resourcesService: ResourcesService,
    private _router: Router,
    private _functionsService: FunctionsService,
    private _gdelService: GdelService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.equipment = null;
    
    this.equipmentDetailsEnabled = true;
    this.relatedDocumentsTableEnabled = true;
    this.equipmentImagesGalleryEnabled = true;
    this.securityCriticalityEnabled = true;
  }

  ngOnInit(): void {
    this.getEquipment();

    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('Ocurrió un error inesperado (1).');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == 'S002V01M07GEEQ');
            if(modPerm.length > 0){
              let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F01ADEQ');
              if(funPerm.length > 0){
                let equipmentDetailsEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02DEEQ');
                if(equipmentDetailsEnabled.length > 0){
                  this.equipmentDetailsEnabled = equipmentDetailsEnabled[0].access > 0;
                }
                
                let equipmentImagesGalleryEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P03GIEQ');
                if(equipmentImagesGalleryEnabled.length > 0){
                  this.equipmentImagesGalleryEnabled = equipmentImagesGalleryEnabled[0].access > 0;
                }
                
                let relatedDocumentsTableEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P04TDRE');
                if(relatedDocumentsTableEnabled.length > 0){
                  this.relatedDocumentsTableEnabled = relatedDocumentsTableEnabled[0].access > 0;
                }
              }

              let securityCriticalityEnabled = modPerm[0].children.filter(item => item.id == 'S002V01F03GCSE');
              if(securityCriticalityEnabled.length > 0){
                this.securityCriticalityEnabled = securityCriticalityEnabled[0].access > 0;
              }
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('Ocurrió un error inesperado (2).');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('Ocurrió un error inesperado (3).');
        }else{
          this._resourcesService.openSnackBar(error.error.msg);
        }
      }
    });

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  }

  async getEquipment(){
    try{
      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = '';
      if(permissionsEnc == '' || permissionsEnc == undefined || permissionsEnc == null){
        permissionsDec = '[]';
      }else{
        permissionsDec = await this._encService.decrypt(permissionsEnc!);
      }
  
      let permissionsArr: Permissions = JSON.parse(permissionsDec);
      if(permissionsArr.permissions != undefined){
        let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M07GEEQ');
        if(modPerm.length > 0){
          let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F01ADEQ');
          if(funPerm.length > 0){
            let equipmentDetailsEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02DEEQ');
            if(equipmentDetailsEnabled.length > 0){
              this.equipmentDetailsEnabled = equipmentDetailsEnabled[0].access > 0;
            }
            
            let equipmentImagesGalleryEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P03GIEQ');
            if(equipmentImagesGalleryEnabled.length > 0){
              this.equipmentImagesGalleryEnabled = equipmentImagesGalleryEnabled[0].access > 0;
            }
            
            let relatedDocumentsTableEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P04TDRE');
            if(relatedDocumentsTableEnabled.length > 0){
              this.relatedDocumentsTableEnabled = relatedDocumentsTableEnabled[0].access > 0;
            }
          }

          let securityCriticalityEnabled = modPerm[0].children.filter(item => item.id == 'S002V01F03GCSE');
          if(securityCriticalityEnabled.length > 0){
            this.securityCriticalityEnabled = securityCriticalityEnabled[0].access > 0;
          }
        }
      }

      let idUser = localStorage.getItem('idusuario')!;
      let equipment: EquipmentDetailsResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultOnly(
        this._data.code,
        idUser,
        1
      ));

      this.hasError = equipment.error;
      this.errorStr = equipment.msg;
      
      if(!this.hasError){
        this.equipment = equipment.response;
        this.equipment.CODIGO = await this._encService.decrypt(this.equipment.CODIGO);

        let codeType = parseInt(this.equipment.TIPO_CODIGO);
        this.equipment.TIPO_CODIGO = `${this.codeTypes[codeType as never]} (${this.equipment.TIPO_CODIGO})`;
        this.equipment.TIPO_EQUIPAMIENTO = await this._encService.decrypt(this.equipment.TIPO_EQUIPAMIENTO);
        this.equipment.MODELO = await this._encService.decrypt(this.equipment.MODELO);
        this.equipment.ID_EQUIPAMIENTO = await this._encService.decrypt(this.equipment.ID_EQUIPAMIENTO);

        let imagesGallery: string[] = JSON.parse(equipment.response.GALERIA_IMAGENES as string);
        let imagesGalleryFn: string[] = [];

        for(const image of imagesGallery){
          let imageEncrypted = await this._encService.isEncrypted(image);
          if(imageEncrypted){
            let imageStr = await this._encService.decrypt(image);
            imagesGalleryFn.push(imageStr);
          }else{
            imagesGalleryFn.push(image);
          }
        }

        this.equipment.GALERIA_IMAGENES = imagesGalleryFn;
      }

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

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

  async updateEquipmentCriticality(event: any){
    try{
      let dataDec = await this._encService.decrypt(event);
      let dataArr = dataDec.split('|');

      if(dataArr.length < 2){
        this._resourcesService.openSnackBar('Los datos seleccionados son inválidos.');
        return;
      }

      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('equipment_code', dataArr[1]);
      formData.append('criticality', dataArr[0]);

      await lastValueFrom(this._equipmentManagementService.equipmentUpdateSecurityCriticality(formData));
      this._resourcesService.openSnackBar('La criticidad de seguridad el equipamiento se actualizó correctamente.');
      
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';

      this.getEquipment();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (6).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (7).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async generateFile(event: any){
    try{
      this._resourcesService.openSnackBar('Generando archivo...');

      let dataArr = event.split('|');
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('file_type', dataArr[1]);
      formData.append('file_data', dataArr[0]);

      let response = await lastValueFrom(this._equipmentManagementService.equipmentGenerateEquipmentFile(formData));
      if(response.error){
        this._resourcesService.openSnackBar(response.msg);
      }else{
        let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(
          response.response.fileID,
          idUser,
          1
        ));

        let download = this._document.getElementById('download') as HTMLAnchorElement;
  
        download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
        download.download = response.response.fileID;
        download.click();
      }
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (8).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (9).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
