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

@Component({
    selector: 'app-plane-uploader',
    templateUrl: './plane-uploader.component.html',
    styleUrl: './plane-uploader.component.css',
    standalone: false
})
export class PlaneUploaderComponent {
  isUploading: boolean;
  tempFile: TempFileInfo | null;
  planeLevelControl: FormControl;

  constructor(
    private _resourcesService: ResourcesService,
    private _gdelService: GdelService,
    private _dialogRef: MatDialogRef<PlaneUploaderComponent>,
    private _encService: EncService,
  ) {
    this.isUploading = false;
    this.tempFile = null;
    this.planeLevelControl = new FormControl('', Validators.required);
  }

  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 maxFileSize = 1048576 * maxSizeMB;
      let fileSize = event.target.files[0].size;

      if(extStr.toLowerCase() != 'svg'){
        this._resourcesService.openSnackBar(`Los archivos relacionados a los planos de estaciones únicamente deben tener extensión SVG.`);
        return;
      }

      if(fileSize > maxFileSize){
        this._resourcesService.openSnackBar(`El tamaño del archivo supera el límite de ${maxSizeMB} MB`);
      }else{
        let alreadyAttached = false;
        if(this.tempFile != null){
          alreadyAttached = this.tempFile.name == event.target.files[0].name && this.tempFile.size == this._resourcesService.formatBytes(event.target.files[0].size);
        }

        if(alreadyAttached){
          this._resourcesService.openSnackBar("El archivo seleccionado ya fue adjuntado.");
        }else{
          this.isUploading = true;
          this.uploadTmp(event.target.files[0]);
        }
      }
    }
  }

  async uploadTmp(fileData: any){
    try{
      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._resourcesService.formatBytes(fileData.size),
        };

        this.tempFile = uploadedFile
      }

      this.isUploading = false;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado. 9');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado. 10');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
      this.isUploading = false;
    }
  }

  async deleteFile(id: string){
    try{
      let idUser = localStorage.getItem('idusuario');

      await lastValueFrom(this._gdelService.deleteTempFile({
        'id_user': idUser!,
        'id_file': id,
        'linea': 1,
      }));

      this._resourcesService.openSnackBar('El archivo se eliminó correctamente.');
      this.tempFile = null;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado. 11');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado. 12');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async savePlane(){
    let dataObj = {
      file: this.tempFile,
      level: this.planeLevelControl.value,
    };

    let dataStr = JSON.stringify(dataObj);
    let dataEnc = await this._encService.encrypt(dataStr);
    this._dialogRef.close(dataEnc);
  }
}
