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, lastValueFrom } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { DataFormDetails, DetailsArtitle } from 'src/app/interfaces/acquisition-management/artitle.interface';
import { ResourcesService } from '../../../../../services/resources/resources.service';
import { HttpErrorResponse } from '@angular/common/http';
import { CataloguesService } from 'src/app/services/catalogues.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { CatalogueCoins, CatalogueCoinsDocument, ResponseDataCatalogueCoins } from 'src/app/interfaces/catalogue.interface';

@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 isLoading: boolean;
  public type:string;
  public filteredOptions?: Observable<string[]>;
  public arrCatalogCoins: Array<CatalogueCoins>;
  public catalogCoinsStr: Array<string>;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: DataFormDetails,
    private _dialogRef: MatDialogRef<any>,
    public resourcesService: ResourcesService,
    private _cataloguesService: CataloguesService,
    private _encService: EncService,

  ) {
    this.type = this.dataDialog.itemElement === undefined ? 'REG' : 'MOD';
    this.formGroup = this.createFormGroup();
    this.arrCatalogCoins = [];
    this.catalogCoinsStr = [];

    this.isLoading = true;
  }

  ngOnInit(): void {
    this.getCoinsActives();
    this.setData();

    this.filteredOptions = this.formGroup.controls['MONEDA'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.catalogCoinsStr.filter(option => option.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),
      PRECIO : new FormControl( '', Validators.required),
      MONTO_MINIMO : new FormControl( '', Validators.required),
      CARACTERISTICAS : new FormControl( '', Validators.required),
      ESTADO: new FormControl('Nuevo', Validators.required),
    });
  }

  private setData(){
    if (this.type === 'MOD') {
      this.formGroup.controls['NO'].setValue(this.dataDialog.itemElement!.NO);
      this.formGroup.controls['CODIGO'].setValue(this.dataDialog.itemElement!.CODIGO);
      this.formGroup.controls['MODELO'].setValue(this.dataDialog.itemElement!.MODELO);
      this.formGroup.controls['MONEDA'].setValue(this.dataDialog.itemElement!.MONEDA);
      this.formGroup.controls['PRECIO'].setValue(this.dataDialog.itemElement!.PRECIO);
      this.formGroup.controls['MONTO_MINIMO'].setValue(this.dataDialog.itemElement!.MONTO_MINIMO);
      this.formGroup.controls['CARACTERISTICAS'].setValue(this.dataDialog.itemElement!.CARACTERISTICAS);

      if (this.dataDialog.itemElement!.ESTADO !== 'Nuevo') {
        this.formGroup.controls['ESTADO'].setValue('Modificado');
      }
    }
  }

  private async getCoinsActives() {
    this.isLoading = true;
     
    let catalogCoins = localStorage.getItem('catalogo_moneda');                
    if (catalogCoins === null) {
      const idUser:string = this.resourcesService.getUser();
      const line: number = parseInt(this.resourcesService.getLineNumber());
      await lastValueFrom(this._cataloguesService.getGeneralCatalogueInfo('c_Moneda', 5, idUser, line)).then(
        async (responseData:ResponseDataCatalogueCoins) => {
          if (!responseData.error) {    
            let arrCataloguesCoinsDocument:Array<CatalogueCoinsDocument> = responseData.response;
            let arrCataloguesCoins:Array<CatalogueCoins> = arrCataloguesCoinsDocument.map((cataloguesCoins:CatalogueCoinsDocument) =>  {
              return {
                C_MONEDA: cataloguesCoins.c_Moneda,
                DESCRIPCION: cataloguesCoins.Descripción,
                DECIMALES: cataloguesCoins.Decimales,
                PORCENTAJE_VARIACION: cataloguesCoins.Porcentaje_variación,
                FECHA_INICIO_DE_VIGENCIA: cataloguesCoins.Fecha_inicio_de_vigencia,
                FECHA_FIN_DE_VIGENCIA: cataloguesCoins.Fecha_fin_de_vigencia,
              }
            });
            arrCataloguesCoins = arrCataloguesCoins.filter((cataloguesCoins:CatalogueCoins) =>  
              cataloguesCoins.C_MONEDA !== null && cataloguesCoins.DESCRIPCION !== null
            );

            const strCataloguesCoins:string = JSON.stringify(arrCataloguesCoins);
            let encCataloguesCoins:string = await this._encService.encrypt(strCataloguesCoins);
            localStorage.setItem('catalogo_moneda', encCataloguesCoins);
            catalogCoins = encCataloguesCoins;
          } else {
            this.resourcesService.openSnackBar(`${responseData.msg}`);
          }
        }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
      );
    } 

    const strCataloguesCoins:string = await this._encService.decrypt(catalogCoins!);
    this.arrCatalogCoins = JSON.parse(strCataloguesCoins);
    this.catalogCoinsStr = [];
    this.arrCatalogCoins = this.arrCatalogCoins.map((catalogCoins:CatalogueCoins) => {
      this.catalogCoinsStr.push(`(${catalogCoins.C_MONEDA}) ${catalogCoins.DESCRIPCION}`);
      return {
        C_MONEDA: catalogCoins.C_MONEDA,
        DESCRIPCION: catalogCoins.DESCRIPCION,
      }
    });

    this.isLoading = false;
    
  }

  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.formGroup.controls['NO'].value) {
          element = this.formGroup.value;
        }
        arrDetails.push(element);
      });
      this.dataDialog.element.DETAILS = arrDetails
    }
    this._dialogRef.close(this.dataDialog.element);
  }

  public validatePrice(){
    let priceMinimum: number = parseFloat(this.formGroup.controls['MONTO_MINIMO'].value);
    let price: number = parseFloat(this.formGroup.controls['PRECIO'].value);
    this.formGroup.controls['MONTO_MINIMO'].setValidators([Validators.min(price)]);

    if ( priceMinimum < price) {
      this.formGroup.controls['MONTO_MINIMO'].setErrors({'min': true});
    } else{
      this.formGroup.controls['MONTO_MINIMO'].setErrors(null);
    }
    this.formGroup.controls['MONTO_MINIMO'].markAsTouched();
  }

  public minimumAmount() {
    let price: number = parseFloat(this.formGroup.controls['PRECIO'].value);
    this.formGroup.controls['MONTO_MINIMO'].setValidators([Validators.min(price)]);
  }
}

export interface ResponseDataCoins {
  error: boolean;
  msg: string;
  response: Array<DataCoins>;
}

export interface DataCoins {
  c_Moneda: string;
  Descripción: string;
  Decimales?: string;
  Porcentaje_variación?: string;
  Fecha_inicio_de_vigencia?: string;
  Fecha_fin_de_vigencia?: string;
}