import { ModuleFunction, ModuleFunctionsResponse } from './../../interfaces/module-functions.interface';
import { Permissions } from './../../interfaces/permissions.interface';
import { Router } from '@angular/router';
import { EncService } from 'src/app/services/enc/enc.service';
import { lastValueFrom } from 'rxjs';
import { Submodules, SubmodulesResponse } from './../../interfaces/submodules.interface';
import { ModulesService } from './../../services/modules.service';
import { Component, OnInit } from '@angular/core';

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

  submodules: Submodules[];
  functions: ModuleFunction[];

  constructor(
    private _modulesService: ModulesService,
    private _encService: EncService,
    private router: Router
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";

    this.submodules = [];
    this.functions = [];
  }

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

  async getSubmodules(){
    try{
      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = await this._encService.desencriptar(permissionsEnc!);
      let permissionsArr: Permissions = JSON.parse(permissionsDec);

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

      let idEnc = localStorage.getItem('idusuario');
      let idShort = await lastValueFrom(this._encService.shortEncrypt(idEnc!));

      let functions: ModuleFunctionsResponse = await lastValueFrom(this._modulesService.getModuleFunctions(
        modShort.response.encrypted, 
        idShort.response.encrypted, 
        1
      ));

      this.hasError = functions.error;
      if(this.hasError){
        this.errorStr = functions.msg;
        this.isLoading = false;
      }else{
        this.functions = functions.response;
        this.isLoading = false;
      }
    }catch(error: any){
      this.isLoading = false;
      this.hasError = true;

      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;
      }
    }
  }

  openFunction(funcID: string){
    let route = funcID.substring(10, funcID.length);
    this.router.navigate([`sam/ADSI/${route}`]);
  }

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

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