import { Component, Inject, OnInit } from '@angular/core';
import { TempFileInfo } from '../../../../interfaces/temp-file-info.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DOCUMENT } from '@angular/common';
import { EmployeeService } from '../../../../services/personal-management/employee.service';
import { ResourcesService } from '../../../../services/resources.service';
import { EncService } from '../../../../services/enc.service';
import { FunctionsService } from '../../../../services/functions.service';
import { GdelService } from '../../../../services/gdel.service';
import { ResponseDataEmployee } from '../../../../interfaces/personal-managment/employee.interface';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-documents-employee',
    templateUrl: './documents-employee.component.html',
    styleUrl: './documents-employee.component.css',
    standalone: false
})
export class DocumentsEmployeeComponent implements OnInit {
  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;
  public attached: TempFileInfo[];
  public employeeName: string;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    @Inject(DOCUMENT) private _document: Document,
    private _employeeService: EmployeeService,
    private _resourcesService: ResourcesService,
    private _encService: EncService,
    private _functionsService: FunctionsService,
    private _gdelService: GdelService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.attached = [];
    this.employeeName = "";
  }

  ngOnInit(): void {
    this.init(this._data.employeeName);
  }

  async init(nameEnc: string){
    let nameDec = await this._encService.decrypt(nameEnc);
    this.employeeName = nameDec;
    
    this.getEmployee(this._data.idEmployee);
  }

  async getEmployee(idEmployee: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      const line: number = 1;
      let employee: ResponseDataEmployee = await lastValueFrom(this._employeeService.getEmployeeById(idEmployee, idUser, line));
      
      this.hasError = employee.error;
      this.errorStr = employee.msg;

      if(!this.hasError){        
        let attached = JSON.parse(employee.response.DOCUMENTS);
        for(const doc of attached){
          let idDec = await this._encService.decrypt(doc.FILE_ID);
          let file: TempFileInfo = {
            id: doc.FILE_ID,
            name: idDec,
            size: this.formatBytes(doc.FILE_SIZE),
            type: doc.FILE_TYPE
          };

          this.attached.push(file);
        }
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  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{
      let idUser = localStorage.getItem('idusuario')!;
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(idFile, idUser, 1));
      let download = this._document.getElementById('file') as HTMLAnchorElement;
      
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = "";
      download.click();
    }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);
      }
    }
  }
}
