import { Component, EventEmitter, Input, Output, Inject, OnInit } from '@angular/core';
import { InfoUpload } from 'src/app/interfaces/upload-files.interface';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { UploadFilesService } from 'src/app/services/upload-files.service';

@Component({
  selector: 'app-upload-file',
  templateUrl: './upload-file.component.html',
  styleUrls: ['./upload-file.component.css']
})
export class UploadFileComponent implements OnInit {

  @Output() public dataValue: EventEmitter<Array<InfoUpload | string>> = new EventEmitter();

  @Input() public textLabel: string;
  @Input() public multiFiles: boolean;
  @Input() public limitFiles: number;
  @Input() public showNameFileToLabel: boolean;
  @Input() public extension: string;
  @Input() public icon: string;

  public inputFileDisable: boolean;
  public arrFilesSelected: Array<InfoUpload>;
  public arrStrFilesSelected: Array<string>;

  constructor(
    public resourcesService: ResourcesService,
    private _uploadFilesService: UploadFilesService,
  ) {
    this.textLabel = 'Click Aquí para Subir';
    this.multiFiles = false;
    this.limitFiles = 0;
    this.showNameFileToLabel = false;
    this.extension = '.png,.jpg';

    this.arrFilesSelected = [];
    this.arrStrFilesSelected = [];
    this.inputFileDisable = false;
    this.icon = 'file_upload';

  }

  ngOnInit(): void {
    this._uploadFilesService.arr$.subscribe( arrImages => {
      let arrImagesData: Array<any> = [];
      arrImages.forEach((element : InfoUpload | string) => {
        if (typeof element === 'string') {
          arrImagesData.push(element);
        } else {
          arrImagesData.push(element);
        }
      });
      if (typeof arrImagesData[0] === 'string') {
        this.arrStrFilesSelected = arrImagesData;
      } else {
        this.arrFilesSelected = arrImagesData;
      }
    });
    
  }

  public clickToLoadFile() {
    if (!this.inputFileDisable || this.showNameFileToLabel) {
      document.getElementById('upfile')?.click();
    }
  }



  public async loadImg(event: any) {

    //Verifica cuantos archivos se seleccionaron
    let arrFiles: Array<File> = Array.from(event.target.files);

    let contFilesActives: number = 0;
    if (!this.showNameFileToLabel) {
      this.arrFilesSelected.map((elementFiles: InfoUpload) => {
        if (elementFiles.status !== 'Eliminado') {
          contFilesActives ++;
        }
      });  
    }
    

    if (contFilesActives >= this.limitFiles ) {
      this.resourcesService.openSnackBar(`No se puede ingresar más de ${this.limitFiles} ${this.limitFiles == 1 ? 'archivo' : 'archivos'}`);
      return;
    }

    if (this.showNameFileToLabel && arrFiles.length > 0) {
      this.arrFilesSelected = [];
      this.textLabel = '';
    }

    // Se iteran los documentos selccionados
    arrFiles.forEach(async (fileSelected: File, index: number) => {

      // Se convierten los documentos seleccionados en base64
      await this.resourcesService.convertisBase64(fileSelected).then((document: any) => {
        // Seguardan en el arreglo para ser mostrado en la interfaz
        this.arrFilesSelected.push({
          codeFile: '',
          nameFile: fileSelected.name,
          base64File: document.base,
          file: fileSelected,
          status: 'Activo'
        });

        if (this.showNameFileToLabel) {
          this.textLabel += `${fileSelected.name};`;
        }
        // Si ya se llegó al limite, entonces se deshabilita el campo
        this.inputFileDisable = this.arrFilesSelected.length == this.limitFiles;

        if (this.showNameFileToLabel && index == arrFiles.length -1) {
          if (this.arrFilesSelected.length > 0) {
            this.textLabel = this.textLabel.substring( 0, this.textLabel.length -1 );
          } else if (this.arrFilesSelected.length == 0) {
            this.textLabel = this.textLabel;
          }
        }
        this.dataValue.emit( this.arrFilesSelected );
      });
    });
    return;
  }


  public deleteImage(index: number) {
    this.arrFilesSelected[index].status = 'Eliminado';
    this.dataValue.emit( this.arrFilesSelected );
  }
}


