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/acquisition/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 catalogo = catalogoMonedas;
    this.arrCatalogoMonedas = catalogo.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();
      }),
    );

  }

  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.type === 'MOD' ? this.dataDialog.itemElement!.NO : this.dataDialog.element.DETAILS.length + 1 , Validators.required),
      'CODIGO' : new FormControl(this.type === 'MOD' ? this.dataDialog.itemElement!.CODIGO : '', Validators.required),
      'MODELO' : new FormControl(this.type === 'MOD' ? this.dataDialog.itemElement!.MODELO : '', Validators.required),
      'MONEDA' : new FormControl(this.type === 'MOD' ? this.dataDialog.itemElement!.MONEDA : '', Validators.required),
      'CANTIDAD' : new FormControl(this.type === 'MOD' ? this.dataDialog.itemElement!.CANTIDAD : '', Validators.required),
      'PRECIO' : new FormControl(this.type === 'MOD' ? this.dataDialog.itemElement!.PRECIO : '', Validators.required),
      'CARACTERISTICAS' : new FormControl(this.type === 'MOD' ? this.dataDialog.itemElement!.CARACTERISTICAS : '', Validators.required),
      'ESTADO': new FormControl('Activo', Validators.required),
    });
  }

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