import { AdvicesService } from './../../../../../services/advices.service';
import { CataloguesService } from './../../../../../services/catalogues.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Component, Inject, OnInit } from '@angular/core';
import { lastValueFrom } from 'rxjs';
import { apiTemp } from 'src/environments/environment';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-loading-dialog',
  templateUrl: './loading-dialog.component.html',
  styleUrls: ['./loading-dialog.component.css']
})
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 _snackBar: MatSnackBar,
    private _gdelService: GdelService,
  ) { }

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

  openSnackBar(msg: string){
    this._snackBar.open(msg, 'Cerrar', {
      duration: 5000
    })
  }

  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 = `http://git.ittec.mx/sam/public/api/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.openSnackBar(msg);
    }
  }
}
