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

@Component({
  selector: 'app-documents-employee',
  templateUrl: './documents-employee.component.html',
  styleUrls: ['./documents-employee.component.css']
})
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')!;
      let employee: ResponseDataEmployee = await lastValueFrom(this._employeeService.getEmployeeById(idEmployee, idUser));
      
      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;
    }
  }

  buildDate(date: string): string{
    return this._functionsService.orderDate(date);
  }

  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);
      }
    }
  }
}
