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

interface Attached{
  id: string;
  name: string;
  size: string;
}
@Component({
    selector: 'app-advice-alert',
    templateUrl: './advice-alert.component.html',
    styleUrl: './advice-alert.component.css',
    standalone: false
})
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 _encService: EncService,
    private _advicesService: AdvicesService,
    private _resourcesService: ResourcesService,
  ) {
    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 idEnc = localStorage.getItem('idusuario')!;

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

      this.downloadEnabled = true;
    }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);
      }
      this.downloadEnabled = true;
    }
  }
}
