import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Component, OnInit, Inject } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { lastValueFrom } from 'rxjs';
import { EncService } from 'src/app/services/enc/enc.service';
import { SubmoduleFunctionsResponse } from 'src/app/interfaces/submodule-functions.interface';
import { ModulesService } from 'src/app/services/modules.service';

@Component({
  selector: 'app-submodule-functions',
  templateUrl: './submodule-functions.component.html',
  styleUrls: ['./submodule-functions.component.css']
})
export class SubmoduleFunctionsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  functions: any[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _snackBar: MatSnackBar,
    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;
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500, 
    })
  }
}
