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/artitle.interface';
import { ProviderInformation, ResponseDataProviderInformation } from 'src/app/interfaces/acquisition-management/provider.interface';
import { UnitService } from 'src/app/services/acquisition-management/unit.service';
import { ProviderService } from 'src/app/services/acquisition-management/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 textImgUpdate: string;
  public imgBase: string;
  public textLabel: string;
  public textoImagenMostrada: string;

  private isChangeImg: boolean;

  public imagen: any = null;

  public arrProvider: Array<ProviderInformation>;
  public arrUnits: Array<UnitData>;

  public formGroupInformation: FormGroup;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: InformationArtitle,
    private _providerServices: ProviderService,
    public resourcesService: ResourcesService,
    private _unitService: UnitService,
  ) {
    this.type = this.dataDialog === undefined ? 'REG' : 'MOD';
    this.title = 'Registro de Menú';
    this.imgBase = 'assets/img/empty-img.svg';
    this.textLabel = 'Subir imagen';
    this.textImgUpdate = '';
    this.textoImagenMostrada = '';
    this.formGroupInformation = this.createFormGroup();
    this.arrProvider = [];
    this.arrUnits = [];
    this.isChangeImg = false;
  }

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

  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_UNIDAD?.setValue(this.dataDialog.TIPO_UNIDAD);
    this.PROVEEDOR?.setValue(objProvider);
    this.COMPRA_WEB?.setValue(this.dataDialog.COMPRA_WEB);
    this.ESTADO?.setValue('Modificado');
    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_UNIDAD': new FormControl('', Validators.required),
      'PROVEEDOR': new FormControl('', Validators.required),
      'COMPRA_WEB': new FormControl(false),
      'ESTADO': new FormControl('Nuevo', Validators.required),
      'DETAILS': new FormControl([]),
    });
  }

  public setImage (image:string) {
    if (image === 'assets/img/empty-img.svg') {
      return image;
    } else  if (image.includes('data:image')){
      return image;
    }else{
      return 'http://192.168.1.4:8000/storage/GEAD/FO/' + image;
    }
  }

  private async getUnits() {
    await lastValueFrom(this._unitService.getUnitsActives()).then(
      (responseData: ResponseDataUnit) => {
        this.arrUnits = responseData.response;
      }, (error:HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  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.resourcesService.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('');
    }
  }

  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_UNIDAD() { return this.formGroupInformation.get('TIPO_UNIDAD');}
  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');}
}

export interface ResponseDataUnit {
  error: boolean;
  msg: string;
  response: Array<UnitData>;
}
export interface UnitData {
  ID_UNIDAD: number;
  UNIDAD: string;
  USUARIO_REGISTRA: string;
  FECHA_REGISTRA: string;
  USUARIO_MODIFICA: string;
  FECHA_MODIFICA: string;
}
