import { Component, OnInit } from '@angular/core';
import { ResourcesService, ResponseData } from '../../../../../services/resources.service';
import { AcquisitionService } from '../../../../../services/acquisition-management/acquisition.service';
import { MatDialogRef } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-artitle-load',
    templateUrl: './artitle-load.component.html',
    styleUrl: './artitle-load.component.css',
    standalone: false
})
export class ArtitleLoadComponent implements OnInit {
  public titleFile: string;
  public dataFile!: File;
  private fileBase: string;
  public isLoading: boolean;
  
  constructor( public resourcesService: ResourcesService, private _artitleService: AcquisitionService, private _dialogRef: MatDialogRef<ArtitleLoadComponent> ) {
    this.titleFile = '';
    this.fileBase = '';
    this.isLoading = false;
  }

  ngOnInit(): void {
  }

  public clearInputFile() {
    this.dataFile = undefined!;
    this.titleFile = '';

    const elementInputFile: HTMLInputElement = <HTMLInputElement>document.getElementById('inputFile')!;
    elementInputFile.value = '';

  }

  public openExplorer() {
    const elementInputFile: HTMLElement = document.getElementById('inputFile')!;
    elementInputFile.click();
  }

  public loadZip( event: any ) {

    this.dataFile = event.target.files[0];
    if (this.dataFile !== undefined) {
      this.convertisBase64(this.dataFile).then((image: any) => {
        this.fileBase = image.base;
      });

      this.titleFile = this.dataFile.name;
    }else{
      this.titleFile = '';
    }

  }

  private convertisBase64 = async ($event: any) => new Promise((resolve) => {
    try {
      let reader = new FileReader();
      reader.readAsDataURL($event);
      reader.onload = () => { resolve({ base: reader.result }); };
      reader.onerror = () => { resolve({ base: null }); };
    } catch (error) {
      return null
    }
    return resolve;
  });

  public async generateArtitles() {
    this.isLoading = true;

    let formData = new FormData();
    formData.append('FILE_ZIP', this.dataFile);
    formData.append('USUARIO', this.resourcesService.getUser());
    formData.append('NUMERO_LINEA', '1');

    await lastValueFrom(this._artitleService.generateArtitles(formData)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar('¡Registro de Carga Masiva Exitoso!');
          this._dialogRef.close(true);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateArtitles();
        }
      }
    );
  }
}
