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 } 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
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.submodules = [];
  }

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

  async getSubmodules(){
    try{
      let moduleEnc = await this._encService.encriptar('S002V01M02USUPER');
      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);
  }
}
