import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { DetailsLocation, ResponseDataGetDetailsLocation } from '../../../../interfaces/inventory-management/location-stock.interface';
import { ResourcesService } from '../../../../services/resources.service';
import { InventoryManagementService } from '../../../../services/inventory-management/inventory-management.service';
import { EncService } from '../../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-details-history-location',
    templateUrl: './details-history-location.component.html',
    styleUrl: './details-history-location.component.css',
    standalone: false
})
export class DetailsHistoryLocationComponent implements OnInit {
  public isLoading: boolean;
  public formGroup: FormGroup;

  constructor(
    @Inject(MAT_DIALOG_DATA) public detailsLocation: DetailsLocation,
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
    private _dialogReg: MatDialogRef<boolean>,
    private _encService: EncService,
  ) {
    this.isLoading = false;
    this.formGroup = this._createFormGroup();
  }

  private _createFormGroup(): FormGroup {
    return new FormGroup({
      'ID_STOCK': new FormControl(''),
      'ID_UBICACION': new FormControl(''),
      'CODIGO_EQUIPAMIENTO': new FormControl(''),
      'ALMACEN': new FormControl(''),
      'AREA': new FormControl(''),
      'NIVEL': new FormControl(''),
      'ZONA': new FormControl(''),
    });
  }

  async ngOnInit() {
    this.isLoading = true;
    await this.getDetaisLocation();
    this.isLoading = false;
  }

  public async getDetaisLocation() {
    const encStock: string = await this._encService.encrypt(this.detailsLocation.idStock);
    const encLocation: string = await this._encService.encrypt(this.detailsLocation.idLocation);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getDetaisLocation(encStock, encLocation, user, line)).then(
      (responseData: ResponseDataGetDetailsLocation) => {
        if (!responseData.error && Object.keys(responseData.response).length > 0) {

          this.formGroup.controls['ID_STOCK'].setValue(`#${this.detailsLocation.idStock}`);
          this.formGroup.controls['ID_UBICACION'].setValue(`#${this.detailsLocation.idLocation}`);
          this.formGroup.controls['CODIGO_EQUIPAMIENTO'].setValue(responseData.response.CODIGO_EQUIPAMIENTO);
          this.formGroup.controls['ALMACEN'].setValue(responseData.response.ALMACEN);
          this.formGroup.controls['AREA'].setValue(responseData.response.AREA); 
          this.formGroup.controls['NIVEL'].setValue(responseData.response.NIVEL);
          this.formGroup.controls['ZONA'].setValue(responseData.response.ZONA);

        } else if (!responseData.error && Object.keys(responseData.response).length === 0) {
          this.resourcesService.openSnackBar(`No existe información.`);
          this._dialogReg.close(false);
          return;
          
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getDetaisLocation();
        }
      }
    );
  }
}
