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';

@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, 
    private _snackBar: MatSnackBar,
    private _encService: EncService,
    private _cataloguesService: CataloguesService,
    private _advicesService: AdvicesService,
  ) { }

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

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

  async downloadCatalogue(id: string){
    try{
      let idEnc = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc!));

      let downloadToken = await lastValueFrom(this._advicesService.getDownloadToken(id, shortEnc.response.encrypted, 1));
      this.downloadURI = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${shortEnc.response.encrypted}/1`;
      console.log(downloadToken);
      /*let idEnc = await this._encService.encriptar(id);
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc));
      
      let idUserEnc = localStorage.getItem('idusuario');
      let idUserShort = await lastValueFrom(this._encService.shortEncrypt(idUserEnc!));

      let typeEnc = await this._encService.encriptar('catalogue');
      let shortType = await lastValueFrom(this._encService.shortEncrypt(typeEnc));
      
      let downloadToken = await lastValueFrom(this._cataloguesService.generateDownloadToken(
        idUserShort.response.encrypted, 
        shortType.response.encrypted
      ));
      
      this.downloadURI  = `${apiTemp}download-catalogue/${id}/${idUserShort.response.encrypted}`;
      this.downloadURI += `/1/${downloadToken.response.downloadToken}`;*/
    }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);
    }
  }
}
