import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { EmployeeInfo, ResponseDataEmployee } from 'src/app/interfaces/personal-managment/employee.interface';
import { TempFileInfo } from 'src/app/interfaces/temp-file-info.interface';
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';

@Component({
  selector: 'app-employee-details-dialog',
  templateUrl: './employee-details-dialog.component.html',
  styleUrls: ['./employee-details-dialog.component.css']
})
export class EmployeeDetailsDialogComponent implements OnInit {
  idEmployee: string;
  employeeName: string;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  employee: EmployeeInfo | null;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _employeeService: EmployeeService,
    private _functionsService: FunctionsService,
  ){
    this.idEmployee = "";
    this.employeeName = "";

    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.employee = null;
  }

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

  async init(){
    let employeeName = await this._encService.decrypt(this._data.employeeName);
    this.employeeName = employeeName;

    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){
        this.employee = employee.response;
        this.employee.FECREG = this.buildDate(this.employee.FECREG);

        if(this.employee.FECMOD != null){
          this.employee.FECMOD = this.buildDate(this.employee.FECMOD);
        }
      }

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