import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { Functions, FunctionsResponse } from 'src/app/interfaces/submodules.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { ModulesService } from 'src/app/services/modules.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-failure-analysis',
  templateUrl: './failure-analysis.component.html',
  styleUrls: ['./failure-analysis.component.css']
})
export class FailureAnalysisComponent 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("S002V01M13ANFA");
    const user: string = this.resourcesService.getUser();
    const line: number = parseInt(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}`;
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.errorStr = this.resourcesService.checkErrorsStr(httpErrorResponse)
    );
    this.isLoading = false;
  }

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

}
