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

@Component({
  selector: 'app-equipment-documents',
  templateUrl: './equipment-documents.component.html',
  styleUrls: ['./equipment-documents.component.css']
})
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 = `http://git.ittec.mx/sam/public/api/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.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
