import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { InformationArtitle } from 'src/app/interfaces/acquisition-management/acquisition/artitle.interface';
import { ProviderInformation, ResponseDataProviderInformation } from 'src/app/interfaces/acquisition-management/provider/provider.interface';
import { ProviderService } from 'src/app/services/acquisition-management/provider/provider.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-artitle-description-form.component',
  templateUrl: './artitle-description-form.component.html',
  styleUrls: ['./artitle-description-form.component.css']
})
export class ArtitleDescriptionFormComponent implements OnInit {

  public title: string;
  public type: string;
  public imagen: any = null;
  public imgBase: string = 'assets/img/empty-img.svg';
  public textLabel: string = 'Subir imagen';
  public textImgUpdate: string = '';
  public textoImagenMostrada: string = '';

  public arrProvider: Array<ProviderInformation>;

  public formGroupInformation: FormGroup;

  private isChangeImg: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: InformationArtitle,
    private _providerServices: ProviderService,
    public resourcesService: ResourcesService,
  ) {
    this.title = "Registro de Menú";
    this.type = this.dataDialog === undefined ? 'REG' : 'MOD';
    this.formGroupInformation = this.createFormGroup();
    this.arrProvider = [];
    this.isChangeImg = false;
  }

  async ngOnInit() {
    await this.getProvidersActives();
    if (this.type === 'MOD') {
      this.setDataForm();
    }
  }

  private setDataForm () {
    this.imgBase = this.dataDialog.URLIMAGE;
    this.imagen = this.dataDialog.IMAGEN;
    this.textLabel = this.imagen === null ? this.dataDialog.URLIMAGE : this.imagen.name;

    let objProvider:ProviderInformation = this.arrProvider.find((element:ProviderInformation) => element.NUMERO_PROVEEDOR === this.dataDialog.PROVEEDOR.NUMERO_PROVEEDOR)!;

    this.dataDialog.URLIMAGE = this.dataDialog.URLIMAGE;

    this.NO?.setValue(this.dataDialog.NO);
    this.IMAGEN?.setValue(this.dataDialog.IMAGEN);
    this.URLIMAGE?.setValue(this.dataDialog.URLIMAGE);
    this.DESCRIPCION?.setValue(this.dataDialog.DESCRIPCION);
    this.CARACTERISTICAS?.setValue(this.dataDialog.CARACTERISTICAS);
    this.TIPO?.setValue(this.dataDialog.TIPO);
    this.PROVEEDOR?.setValue(objProvider);
    this.COMPRA_WEB?.setValue(this.dataDialog.COMPRA_WEB);
    this.ESTADO?.setValue(this.dataDialog.ESTADO);
    this.DETAILS?.setValue(this.dataDialog.DETAILS);
  }

  private createFormGroup() {
    return new FormGroup({
      'NO': new FormControl('1', Validators.required),
      'IMAGEN': new FormControl(''),
      'URLIMAGE': new FormControl('assets/img/empty-img.svg', Validators.required),
      'DESCRIPCION': new FormControl('', Validators.required),
      'CARACTERISTICAS': new FormControl(''),
      'TIPO': new FormControl('', Validators.required),
      'PROVEEDOR': new FormControl('', Validators.required),
      'COMPRA_WEB': new FormControl(false),
      'ESTADO': new FormControl('Activo', Validators.required),
      'DETAILS': new FormControl([]),
    });
  }

  public setImage (image:string) {
    if (this.NO?.value.length === 10 && !this.isChangeImg) {
      return 'http://192.168.1.4:8000/storage/GEAD/FO/' + image;
    } else {
      return image;
    }
  }

  private async getProvidersActives() {
    await lastValueFrom(this._providerServices.getProviderActives()).then(
      (responseData:ResponseDataProviderInformation) => {
        this.arrProvider = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  // Ejecuta el input file
  public getFile() {
    document.getElementById("upfile")!!.click();
  }

  // Método para cargar la imagen
  public loadImg(obj: any, event: any) {
    this.imagen = event.target.files[0];
    var file = obj.value;
    if (file !== '') {
      var fileName = file.split("\\");
      this.textLabel = fileName[fileName.length - 1];
      this.convertisBase64(this.imagen).then((image: any) => {
        this.imgBase = image.base
        this.URLIMAGE?.setValue(image.base);
      });
      this.textoImagenMostrada = 'Imagen seleccionada';
      this.IMAGEN?.setValue(this.imagen);
      this.isChangeImg = true;
    } else {
      this.textLabel = "Subir imagen";
      this.imgBase = 'assets/img/empty-img.svg';
      this.textoImagenMostrada = '';
      this.IMAGEN?.setValue('');
      this.URLIMAGE?.setValue('');
    }
  }

  // Mostrar imagen seleccionada
  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;
  });

  get NO() { return this.formGroupInformation.get('NO');}
  get IMAGEN() { return this.formGroupInformation.get('IMAGEN');}
  get URLIMAGE() { return this.formGroupInformation.get('URLIMAGE');}
  get DESCRIPCION() { return this.formGroupInformation.get('DESCRIPCION');}
  get CARACTERISTICAS() { return this.formGroupInformation.get('CARACTERISTICAS');}
  get TIPO() { return this.formGroupInformation.get('TIPO');}
  get PROVEEDOR() { return this.formGroupInformation.get('PROVEEDOR');}
  get COMPRA_WEB() { return this.formGroupInformation.get('COMPRA_WEB');}
  get DETAILS() { return this.formGroupInformation.get('DETAILS');}
  get ESTADO() { return this.formGroupInformation.get('ESTADO');}
}

