import { Component, Inject } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { GetStockBarcode, UpdateStockBarcode } from '../../../../interfaces/inventory-management/barcode-management.interface';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { InventoryManagementService } from '../../../../services/inventory-management/inventory-management.service';
import { EncService } from '../../../../services/enc.service';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-form-barcode',
    templateUrl: './form-barcode.component.html',
    styleUrl: './form-barcode.component.css',
    standalone: false
})
export class FormBarcodeComponent {
  public isLoading: boolean;
  public formGroup: FormGroup;

  constructor(
    @Inject(MAT_DIALOG_DATA) public stockBarcode: GetStockBarcode,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<boolean>,
    private _inventoryManagementService: InventoryManagementService,
    private _encService: EncService,
  ) {
    this.isLoading = false;
    this.formGroup = this._createFormGroup();
  }

  private _createFormGroup() {
    return new FormGroup({
      'BARCODE': new FormControl(this.stockBarcode.CODIGO_BARRA, [Validators.required])
    });
  }

  isValidBarcode(barcode:any) {
    if (barcode.length < 8 || barcode.length > 18 ||
        (
          barcode.length != 8 && barcode.length != 12 &&
          barcode.length != 13 && barcode.length != 14 &&
          barcode.length != 18
        )
    ) {
      return false;
    }
  
    var lastDigit = Number(barcode.substring(barcode.length - 1));
    var checkSum = 0;
    if (isNaN(lastDigit)) { return false; } // not a valid upc/ean
  
    var arr = barcode.substring(0,barcode.length - 1).split("").reverse();
    var oddTotal = 0, evenTotal = 0;
  
    for (var i=0; i<arr.length; i++) {
      if (isNaN(arr[i])) { return false; } // can't be a valid upc/ean we're checking for
  
      if (i % 2 == 0) { oddTotal += Number(arr[i]) * 3; }
      else { evenTotal += Number(arr[i]); }
    }
    checkSum = (10 - ((evenTotal + oddTotal) % 10)) % 10;
  
    // true if they are equal
    return checkSum == lastDigit;
  }

  public save() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de modificar el código de barras?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.updateStockBarcode();
      }
    });
  }

  public async updateStockBarcode() {
    const encStock = await this._encService.encrypt(this.stockBarcode.ID_STOCK);
    const updateStockMaxMin: UpdateStockBarcode = {
      BARCODE: this.formGroup.controls['BARCODE'].value,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    await lastValueFrom(this._inventoryManagementService.updateStockBarcode(encStock, updateStockMaxMin)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Modificación Existosa!`);
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.updateStockBarcode();
        }
      }
    );
  }
}
