import { Component, Inject, OnInit } from '@angular/core';
import { TempFileInfo } from '../../../interfaces/temp-file-info.interface';
import { DOCUMENT } from '@angular/common';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FunctionsService } from '../../../services/functions.service';
import { DocumentManagementService } from '../../../services/document-management.service';
import { ResourcesService } from '../../../services/resources.service';
import { lastValueFrom } from 'rxjs';
import { apiTemp } from '../../../../environments/environment.prod';

@Component({
    selector: 'app-equipment-documents',
    templateUrl: './equipment-documents.component.html',
    styleUrl: './equipment-documents.component.css',
    standalone: false
})
export class EquipmentDocumentsComponent implements OnInit {
  equipment: string;
  documents: TempFileInfo[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    @Inject(DOCUMENT) private _document: Document,
    private _functionsService: FunctionsService,
    private _documentManagementService: DocumentManagementService,
    private _resourcesService: ResourcesService,
  ){
    this.equipment = "";
    this.documents = [];
  }

  ngOnInit(): void {
    this.equipment = this._data.equipment;

    for(const document of this._data.documents as TempFileInfo[]){
      document.size = this._functionsService.formatBytes(parseInt(document.size));
      this.documents.push(document);
    }
  }

  async downloadFile(idFile: string, file: string){
    try{
      this._resourcesService.openSnackBar(`Iniciando la descarga del archivo ${file}...`);

      let idUser = localStorage.getItem('idusuario')!;
      let downloadToken = await lastValueFrom(this._documentManagementService.getDownloadToken(idFile, idUser, 1));
      let download = this._document.getElementById(`download`) as HTMLAnchorElement;
  
      download.href = `${apiTemp}download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = idFile;
      download.click();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (1).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (2).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
