import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { InternationalizationService } from '../../../services/internationalization/internationalization.service';
import { EncService } from '../../../services/enc.service';
import { ModulesService } from '../../../services/modules.service';
import { SubmoduleFunctionsResponse } from '../../../interfaces/submodule-functions.interface';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-selected-function',
    templateUrl: './selected-function.component.html',
    styleUrl: './selected-function.component.css',
    standalone: false
})
export class SelectedFunctionComponent {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  functions: any[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    public interService: InternationalizationService,
    private _encService: EncService,
    private _modulesService: ModulesService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.functions = [];
  }

  ngOnInit(): void {
    this.openMenu(this._data.module, this._data.submodule)
  }

  async openMenu(module: string, submodule: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let modEnc = await this._encService.encrypt(module);
      let subEnc = await this._encService.encrypt(submodule);

      let submoduleFunctions: SubmoduleFunctionsResponse = await lastValueFrom(this._modulesService.getSubmoduleFunctions(
        modEnc,
        subEnc,
        idUser,
        1
      ));

      this.hasError = submoduleFunctions.error;
      this.errorStr = submoduleFunctions.msg;

      if(!this.hasError){
        submoduleFunctions.response.forEach(funct => {
          if(funct.HASSCREENS){
            this.functions.push(funct);
          }
        });
      }
      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }
}
