import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { lastValueFrom } from 'rxjs';
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 { PreventiveMaintenanceService } from 'src/app/services/preventive-maintenance.service';
import { availableFiles } from 'src/environments/environment.prod';

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

  constructor(
    private _snackBar: MatSnackBar,
    private _gdelService: GdelService,
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _dialogRef: MatDialogRef<UploadMaintenancePlanComponent>,
  ) {
    this.isUploading = false;
    this.uploadedFile = null;
    this.instructions = "";
  }

  ngOnInit(): void { 
  }
  
  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.openSnackBar(`Los archivos ${extStr} no están soportados`);
    }else{
      let excelExts = ['xls', 'xlsx', 'csv'];

      if(!excelExts.includes(extStr)){
        this.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.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.openSnackBar("El archivo seleccionado ya fue adjuntado.");
        }else{
          this.uploadTmp(event.target.files[0]);
        }
      }
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    });
  }

  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 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.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.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }

      this.isUploading = false;
    }
  }

  async getMaintenancePlanAnalysis(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let maintenancePlan = await lastValueFrom(this._prevMaintService.getMaintenancePlanAnalysis(
        this.uploadedFile?.id!,
        idUser,
        1
      ));

      if(maintenancePlan.error){
        this.openSnackBar(maintenancePlan.msg);
        this.uploadedFile = null;
      }else{
        this.instructions = JSON.stringify(maintenancePlan.response);
      }
      
      this.isUploading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }

      this.uploadedFile = null;
      this.isUploading = false;
    }
  }

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