import { Component, OnInit } from '@angular/core';
import { TempFileInfo } from '../../../../../interfaces/temp-file-info.interface';
import { GdelService } from '../../../../../services/gdel.service';
import { PreventiveMaintenanceService } from '../../../../../services/preventive-maintenance.service';
import { MatDialogRef } from '@angular/material/dialog';
import { availableFiles } from '../../../../../../environments/environment.prod';
import { ResourcesService } from '../../../../../services/resources.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-upload-maintenance-plan',
    templateUrl: './upload-maintenance-plan.component.html',
    styleUrl: './upload-maintenance-plan.component.css',
    standalone: false
})
export class UploadMaintenancePlanComponent {
  isUploading: boolean;
  uploadedFile: TempFileInfo | null;
  instructions: string;

  constructor(
    private _gdelService: GdelService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _dialogRef: MatDialogRef<UploadMaintenancePlanComponent>,
    private _resourcesService: ResourcesService,
  ) {
    this.isUploading = false;
    this.uploadedFile = null;
    this.instructions = "";
  }
  
  checkFile(event: any){
    let fileTypes = availableFiles;
    let sizes = Object.keys(fileTypes);
    let extensions = Object.values(fileTypes);
    let maxSizeMB = 0;

    let extArr = event.target.files[0].name.split(".").reverse();
    let extStr = extArr[0];

    let i = 0;
    extensions.forEach(ext => {
      let size = parseInt(sizes[i]);

      if(ext.includes(extStr)) maxSizeMB = size;
      i++;
    });

    if(maxSizeMB == 0){
      this._resourcesService.openSnackBar(`Los archivos ${extStr} no están soportados`);
    }else{
      let excelExts = ['xls', 'xlsx', 'csv'];

      if(!excelExts.includes(extStr)){
        this._resourcesService.openSnackBar(`El tipo de archivo cargado no es compatible con Excel`);
      }else{
        let maxFileSize = 1048576 * maxSizeMB;
        let fileSize = event.target.files[0].size;

        if(this.uploadedFile == null){
          this.uploadTmp(event.target.files[0]);
        }else if(fileSize > maxFileSize){
          this._resourcesService.openSnackBar(`El tamaño del archivo supera el límite de ${maxSizeMB} MB`);
        }else if(this.uploadedFile.name == event.target.files[0].name && this.uploadedFile.size == this.formatBytes(event.target.files[0].size)){
          this._resourcesService.openSnackBar("El archivo seleccionado ya fue adjuntado.");
        }else{
          this.uploadTmp(event.target.files[0]);
        }
      }
    }
  }

  async uploadTmp(fileData: any){
    try{
      this.isUploading = true;

      let idUser = localStorage.getItem('idusuario');
      let formData = new FormData();

      formData.append('file', fileData);
      formData.append('id_user', idUser!);
      formData.append('linea', '1');

      let response = await lastValueFrom(this._gdelService.uploadTempFile(formData));

      if(response.error){
        this._resourcesService.openSnackBar(response.msg);
      }else{
        let uploadedFile: TempFileInfo = {
          id: response.response.idArchivo,
          name: fileData.name,
          size: this.formatBytes(fileData.size)
        };

        this.uploadedFile = uploadedFile;
        this.getMaintenancePlanAnalysis();
      }
    }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.isUploading = 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 getMaintenancePlanAnalysis(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let maintenancePlan = await lastValueFrom(this._prevMaintService.getMaintenancePlanAnalysis(
        this.uploadedFile?.id!,
        idUser,
        1
      ));

      if(maintenancePlan.error){
        this._resourcesService.openSnackBar(maintenancePlan.msg);
        this.uploadedFile = null;
      }else{
        this.instructions = JSON.stringify(maintenancePlan.response);
      }
      
      this.isUploading = false;
    }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.uploadedFile = null;
      this.isUploading = false;
    }
  }

  closeDialog(){
    let file = JSON.stringify(this.uploadedFile);
    this._dialogRef.close(`${this.instructions}|${file}`);
  }
}
