import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { GdelService } from '../../../../../services/gdel.service';
import { DOCUMENT } from '@angular/common';
import { lastValueFrom } from 'rxjs';
import { apiTemp } from '../../../../../../environments/environment.prod';
import { ResourcesService } from '../../../../../services/resources.service';

@Component({
    selector: 'app-loading-dialog',
    templateUrl: './loading-dialog.component.html',
    styleUrl: './loading-dialog.component.css',
    standalone: false
})
export class LoadingDialogComponent implements OnInit {
  isLoading = true;
  header = "Obteniendo información del catálogo";
  downloadURI = "";

  constructor(
    @Inject(MAT_DIALOG_DATA) public data: any, 
    @Inject(DOCUMENT) private _document: Document,
    private _gdelService: GdelService,
    private _resourcesService: ResourcesService,
  ) { }

  ngOnInit(): void {
    setTimeout(() => {
      this.isLoading = false;
      this.header = "Error";
    }, 60000);
  }

  async downloadCatalogue(){
    try{
      let download = this._document.getElementById('download') as HTMLAnchorElement;
      let idEnc = localStorage.getItem('idusuario')!;
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(this.data.idCatalogo, idEnc, 1));
      
      download.href = `${apiTemp}download-file/${downloadToken.response.TOKEN}/${idEnc}/1`;
      download.download = "";
      download.click();
    }catch(error: any){
      let msg = "";
      if(error.error == undefined){
        msg = 'Ocurrió un error inesperado';
      }else if(error.error.msg == undefined){
        msg = 'Ocurrió un error inesperado';
      }else{
        msg = error.error.msg;
      }

      this._resourcesService.openSnackBar(msg);
    }
  }
}
