import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

import { DataFormDetails, DataMoneda, DetailsArtitle } from 'src/app/interfaces/acquisition-management/artitle.interface';
import * as catalogoMonedas from 'src/assets/json/catalogo_monedas.json';



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

  public formGroup: FormGroup;
  public type:string;
  public arrCatalogoMonedas: Array<DataMoneda>;
  filteredOptions?: Observable<DataMoneda[]>;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: DataFormDetails,
    private _dialogRef: MatDialogRef<any>,
  ) {
    this.type = this.dataDialog.itemElement === undefined ? 'REG' : 'MOD';
    this.formGroup = this.createFormGroup();
    this.arrCatalogoMonedas = [];
  }

  ngOnInit(): void {
    let catalago = catalogoMonedas;
    this.arrCatalogoMonedas = catalago.arrMoneda;
    this.arrCatalogoMonedas.sort((a,b) => a.moneda.localeCompare(b.moneda));

    this.filteredOptions = this.MONEDA?.valueChanges.pipe(
      startWith(''),
      map((value:any) => {
        const moneda = typeof value === 'string' ? value : value?.moneda;
        return moneda ? this._filter(moneda as string) : this.arrCatalogoMonedas.slice();
      }),
    );

    if (this.type === 'MOD') {
      this.setData();
    }
  }

  public displayFn(user: DataMoneda): string {
    return user && user.moneda ? user.moneda : '';
  }

  private _filter(moneda: string): DataMoneda[] {
    const filterValue = moneda.toLowerCase();

    return this.arrCatalogoMonedas.filter(option => option.moneda.toLowerCase().includes(filterValue));
  }

  private createFormGroup(){
    return new FormGroup({
      'NO' : new FormControl(this.dataDialog.element.DETAILS.length + 1 , Validators.required),
      'CODIGO' : new FormControl( '', Validators.required),
      'MODELO' : new FormControl( '', Validators.required),
      'MONEDA' : new FormControl( '', Validators.required),
      'CANTIDAD' : new FormControl( '', Validators.required),
      'PRECIO' : new FormControl( '', Validators.required),
      'CARACTERISTICAS' : new FormControl( '', Validators.required),
      'ESTADO': new FormControl('Nuevo', Validators.required),
    });
  }

  private setData(){

    this.NO?.setValue(this.dataDialog.itemElement!.NO);
    this.CODIGO?.setValue(this.dataDialog.itemElement!.CODIGO);
    this.MODELO?.setValue(this.dataDialog.itemElement!.MODELO);
    this.CANTIDAD?.setValue(this.dataDialog.itemElement!.CANTIDAD);
    this.MONEDA?.setValue(this.dataDialog.itemElement!.MONEDA);
    this.PRECIO?.setValue(this.dataDialog.itemElement!.PRECIO);
    this.CARACTERISTICAS?.setValue(this.dataDialog.itemElement!.CARACTERISTICAS);

    if (this.dataDialog.itemElement!.ESTADO !== 'Nuevo') {
      this.ESTADO?.setValue('Modificado');
    }
  }

  public openDialog (type:string) {
    if (type === 'REG') {
      this._dialogRef.close(this.dataDialog.element);
      this.dataDialog.element.DETAILS.push(this.formGroup.value);
    }else if (type === 'MOD') {
      let arrDetails: Array<DetailsArtitle> = [];
      this.dataDialog.element.DETAILS.map((element:DetailsArtitle) => {
        if (element.NO === this.NO?.value) {
          element = this.formGroup.value;
        }
        arrDetails.push(element);
      });
      this.dataDialog.element.DETAILS = arrDetails
    }
    this._dialogRef.close(this.dataDialog.element);
  }

  get NO () { return this.formGroup.get('NO');}
  get CODIGO () { return this.formGroup.get('CODIGO');}
  get MODELO () { return this.formGroup.get('MODELO');}
  get CANTIDAD () { return this.formGroup.get('CANTIDAD');}
  get MONEDA () { return this.formGroup.get('MONEDA');}
  get PRECIO () { return this.formGroup.get('PRECIO');}
  get CARACTERISTICAS () { return this.formGroup.get('CARACTERISTICAS');}
  get PROVEEDOR () { return this.formGroup.get('PROVEEDOR');}
  get COMPRA_WEB () { return this.formGroup.get('COMPRA_WEB');}
  get ESTADO () { return this.formGroup.get('ESTADO');}
}
