import { AdvicesService } from './../../../services/advices.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Advice } from 'src/app/interfaces/advice.interface';
import { lastValueFrom } from 'rxjs';
import { DOCUMENT } from '@angular/common';

interface Attached{
  id: string;
  name: string;
  size: string;
}

@Component({
  selector: 'app-advice-alert',
  templateUrl: './advice-alert.component.html',
  styleUrls: ['./advice-alert.component.css']
})
export class AdviceAlertComponent implements OnInit {
  downloadEnabled: boolean;
  dataSource: Attached[] = [];
  displayedColumns: string[] = ['name', 'size', 'actions'];

  constructor(
    @Inject(MAT_DIALOG_DATA) public data: Advice,
    @Inject(DOCUMENT) private _document: Document,
    private _snackBar: MatSnackBar,
    private _encService: EncService,
    private _advicesService: AdvicesService,
    ) { 
      this.downloadEnabled = true;
    }

  ngOnInit(): void {
    let attachedArr: Attached[] = JSON.parse(this.data.ADJUNTOS);
    this.dataSource = attachedArr;
  }

  formatBytes(bytes: number, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  }

  async downloadFile(idFile: string){
    try{
      this.downloadEnabled = false;
      let shortAvi = await lastValueFrom(this._encService.shortEncrypt(idFile));
      let idEnc = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc!));

      let downloadToken = await lastValueFrom(this._advicesService.getDownloadToken(shortAvi.response.encrypted, shortEnc.response.encrypted, 1));
      let download = this._document.getElementById(`download-${idFile}`) as HTMLAnchorElement;
      
      let idDec = await this._encService.desencriptar(idFile);
      
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${shortEnc.response.encrypted}/1`;
      download.download = idDec;
      download.click();

      this.downloadEnabled = true;
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
      this.downloadEnabled = true;
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    });
  }
}
