import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { EquipmentDetails } from '../../../interfaces/equipment-management.interface';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { CodesHistoryComponent } from '../codes-history/codes-history.component';
import { EquipmentDocumentsComponent } from '../equipment-documents/equipment-documents.component';
import { EquipmentMaintenancePlainsComponent } from '../equipment-maintenance-plains/equipment-maintenance-plains.component';
import { CriticalityManagementComponent } from '../criticality-management/criticality-management.component';

@Component({
    selector: 'app-equipment-details',
    templateUrl: './equipment-details.component.html',
    styleUrl: './equipment-details.component.css',
    standalone: false
})
export class EquipmentDetailsComponent implements OnInit {
  @Input() equipment: EquipmentDetails | null;
  @Input() equipmentDetailsEnabled: boolean;
  @Input() equipmentImagesGalleryEnabled: boolean;
  @Input() relatedDocumentsTableEnabled: boolean;
  @Input() securityCriticalityEnabled: boolean;
  @Output() refreshCriticality = new EventEmitter<string>();
  @Output() printFile = new EventEmitter<string>();

  images: string[];
  imageIndex: number;
  screenWidth: number;

  constructor(
    private _matIconRegistry: MatIconRegistry,
    private _domSanitizer: DomSanitizer,
    private _dialog: MatDialog,
    private _encService: EncService,
  ){
    this._matIconRegistry.addSvgIcon(
      'xls',
      this._domSanitizer.bypassSecurityTrustResourceUrl(window.location.origin + "/assets/img/custom_icons/xls.svg")
    );
    this.equipment = null;
    this.equipmentDetailsEnabled = true;
    this.equipmentImagesGalleryEnabled = true;
    this.relatedDocumentsTableEnabled = true;
    this.securityCriticalityEnabled = true;
    this.images = [];
    this.imageIndex = 0;
    this.screenWidth = window.innerWidth;
  }

  ngOnInit(): void {
    this.images = this.equipment?.GALERIA_IMAGENES as string[];
    console.log(this.images);
  }

  onResize(){
    this.screenWidth = window.innerWidth;
  }

  backward(){
    let index = this.imageIndex - 1;
    if(index < 0){
      this.imageIndex = this.images.length - 1;
    }else{
      this.imageIndex = index;
    }
  }

  forward(){
    let index = this.imageIndex + 1;
    if(index > this.images.length - 1){
      this.imageIndex = 0
    }else{
      this.imageIndex = index;
    }
  }

  openCodesHistory(){
    this._dialog.open(CodesHistoryComponent, {
      width: '520px',
      maxWidth: '520px',
      data: {
        equipment: `${this.equipment?.CODIGO} - ${this.equipment?.TIPO_EQUIPAMIENTO} - ${this.equipment?.MODELO} (${this.equipment?.ID_EQUIPAMIENTO})`,
        history: this.equipment?.HISTORIAL_CODIGOS_ARR,
      }
    })
  }

  openDocumentsList(){
    this._dialog.open(EquipmentDocumentsComponent, {
      width: '520px',
      maxWidth: '520px',
      data: {
        equipment: `${this.equipment?.CODIGO} - ${this.equipment?.TIPO_EQUIPAMIENTO} - ${this.equipment?.MODELO} (${this.equipment?.ID_EQUIPAMIENTO})`,
        documents: this.equipment?.DOCUMENTOS
      }
    });
  }

  openMaintenancePlans(){
    this._dialog.open(EquipmentMaintenancePlainsComponent, {
      width: '720px',
      maxWidth: '720px',
      data: {
        equipment: this.equipment!,
      }
    })
  }

  openCriticalityManagement(){
    let dialogRef = this._dialog.open(CriticalityManagementComponent, {
      width: '480px',
      maxWidth: '480px',
      data: {
        equipment: `${this.equipment?.CODIGO} - ${this.equipment?.TIPO_EQUIPAMIENTO} - ${this.equipment?.MODELO} (${this.equipment?.ID_EQUIPAMIENTO})`,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ''){
        this.shouldRefresh(res);
      }
    });
  }

  async shouldRefresh(criticality: string){
    let equipmentCodeEnc = await this._encService.encrypt(this.equipment!.CODIGO);
    let dataEnc = await this._encService.encrypt(`${criticality}|${equipmentCodeEnc}`);
    
    this.refreshCriticality.emit(dataEnc);
  }

  async exportEquipmentDetails(fileType: string){
    let equipmentInfoStr = JSON.stringify(this.equipment!);
    let equipmentInfoEnc = await this._encService.encrypt(equipmentInfoStr);

    this.printFile.emit(`${equipmentInfoEnc}|${fileType}`);
  }
}
