import { Component, OnInit } from '@angular/core';
import { Functions, FunctionsResponse } from '../../interfaces/submodules.interface';
import { ResourcesService } from '../../services/resources.service';
import { EncService } from '../../services/enc.service';
import { ModulesService } from '../../services/modules.service';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { GetDataRegisterArtitle } from '../acquisition-management/dispatch/order-reception/move-stock/move-stock.component';

@Component({
    selector: 'app-inventory-management',
    templateUrl: './inventory-management.component.html',
    styleUrl: './inventory-management.component.css',
    standalone: false
})
export class InventoryManagementComponent implements OnInit {
  public arrFunctions: Array<Functions>;
  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;

  constructor(
    public resourcesService: ResourcesService,
    private _encService: EncService,
    private _modulesService: ModulesService,
    private _router: Router,
  ) {
    this.arrFunctions = [];
    this.isLoading = false;
    this.hasError = false;
    this.errorStr = '';
  }
  
  async ngOnInit() {
    this.isLoading = true;
    const moduleEnc = await this._encService.encrypt("S002V01M08GIST");
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._modulesService.getModuleFunctions(moduleEnc, user, line)).then(
      (responseData: FunctionsResponse) => {
        if (!responseData.error) {
          this.arrFunctions = responseData.response;
        } else {  
          this.errorStr = `${responseData.msg}`;
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.ngOnInit();
        }
      }
    );
    this.isLoading = false;
  }

  public async openMenu(functions: Functions) {
    const idFunction:string = functions.IDFUNCION;
    const route:string = idFunction.substring(10, idFunction.length);
    if (route.length === 4) {
      this._router.navigate([`sam/GIST/${route}`]);
    } else {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener la función del módulo.`);
    }    
  }

  public async registerArtitlesToEquipment() {
    const contentForm: GetDataRegisterArtitle = {
      action: 'new'
    }

    const strContentForm: string = JSON.stringify(contentForm);
    const encContentForm: string = await this._encService.encrypt(strContentForm);

    this._router.navigate([`/sam/GIST/register/${encContentForm}`]);
  }
}
