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

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


  constructor(
    private _encService: EncService,
    private _modulesService: ModulesService,
    private _dialog: MatDialog,
    private _router: Router,
    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.encrypt('S002V01M11GPRS');
      let idEnc = localStorage.getItem('idusuario')!;
      let submodules: SubmodulesResponse = await lastValueFrom(this._modulesService.getSubmodules(
        moduleEnc,
        idEnc, 
        1
      ));

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

      if(!this.hasError){
        this.submodules = submodules.response;
      }
    }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;
    }
  }

  openMenu(submodule: Submodules){
    let dialogRef = this._dialog.open(SubmoduleFunctionsComponent, {
      width: '560px',
      data: {
        module: 'S002V01M11GPRS',
        submodule: submodule.IDSUBMODULO,
      },
    });

    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/GPRS/${idSub}/${idFunc}`]);
      }
    });
  }
}
