import { SubmoduleFunctionsResponse } from './../../interfaces/submodule-functions.interface';
import { MatSnackBar } from '@angular/material/snack-bar';
import { SubmoduleFunctionsComponent } from './../template/menu-item/submodule-functions/submodule-functions.component';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { Submodules, SubmodulesResponse } from './../../interfaces/submodules.interface';
import { EncService } from './../../services/enc/enc.service';
import { lastValueFrom } from 'rxjs';
import { ModulesService } from './../../services/modules.service';
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-users-profiles',
  templateUrl: './users-profiles.component.html',
  styleUrls: ['./users-profiles.component.css']
})
export class UsersProfilesComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  submodules: Submodules[];

  constructor(
    private _modulesService: ModulesService,
    private _encService: EncService,
    private router: Router,
    private _dialog: MatDialog,
    private _snackBar: MatSnackBar,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.submodules = [];
  }

  ngOnInit(): void {
    this.getSubmodules();
  }

  async getSubmodules(){
    try{
      let moduleEnc = await this._encService.encriptar('S002V01M02USPE');
      let modShort = await lastValueFrom(this._encService.shortEncrypt(moduleEnc));
      
      let idEnc = localStorage.getItem('idusuario');
      let idShort = await lastValueFrom(this._encService.shortEncrypt(idEnc!));
      let submodules: SubmodulesResponse = await lastValueFrom(this._modulesService.getSubmodules(
        modShort.response.encrypted,
        idShort.response.encrypted, 
        1
      ));

      this.isLoading = false;
      this.hasError = submodules.error;
      this.errorStr = submodules.msg;

      if(!this.hasError){
        this.submodules = submodules.response;
      }
    }catch(error: any){
      this.isLoading = false;
      this.hasError = true;
      
      let msg = "";
      if(error.error == undefined){
        msg = "Ocurrió un error inesperado.";
      }else{
        msg = error.error.msg;
      }

      this.errorStr = msg;
    }
  }

  openSubmodule(idSub: string){
    let submodule = idSub.replace("S002V01S", "");
    submodule = submodule.substring(2, submodule.length);
    this.router.navigate(["sam/USUPER/", submodule]);
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

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

  async openMenu(submodule: Submodules){
    try{
      let idUser = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));

      let modEnc = await this._encService.encriptar('S002V01M02USPE');
      let modShort = await lastValueFrom(this._encService.shortEncrypt(modEnc));

      let subEnc = await this._encService.encriptar(submodule.IDSUBMODULO);
      let subShort = await lastValueFrom(this._encService.shortEncrypt(subEnc));

      let submoduleFunctions: SubmoduleFunctionsResponse = await lastValueFrom(this._modulesService.getSubmoduleFunctions(
        modShort.response.encrypted,
        subShort.response.encrypted,
        shortEnc.response.encrypted,
        1
      ));

      let dialogRef = this._dialog.open(SubmoduleFunctionsComponent, {
        width: '380px',
        data: {
          FUNCIONES: submoduleFunctions.response,
        },
      });
      
      dialogRef.afterClosed().subscribe(res => {
        if(res != null && res != undefined && res != ""){
          let idFunc = res.IDFUNCION.replace("S002V01F", "");
          idFunc = idFunc.substring(2);
          
          let idSub = submodule.IDSUBMODULO.replace("S002V01S", "");
          idSub = idSub.substring(2);

          this.router.navigate([`sam/USPE/${idSub}/${idFunc}`]);
        }
      });
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }
}
