import { Permissions } from 'src/app/interfaces/permissions.interface';
import { SubmoduleFunctions, 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 } from '@angular/core';
import { SocketService } from 'src/app/services/socket.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';

@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[];
  submodulesAux: Submodules[];

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

  ngOnInit(): void {
    this.getSubmodules();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      let shortID = await lastValueFrom(this._encService.shortEncrypt(localStorage.getItem('idusuario')!));
      let usrInfo: UserConsultResponse = await lastValueFrom(this._profilesService.getUser(shortID.response.encrypted, shortID.response.encrypted, 1));
      let currentProfile = await this._encService.desencriptar(localStorage.getItem('perfil')!);

      if(parseInt(currentProfile) != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.desencriptar(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        try{
          let shortProf = await lastValueFrom(this._encService.shortEncrypt(localStorage.getItem('perfil')!));
          let profInfo: ProfileInterface = await lastValueFrom(this._profilesService.getProfile(
            shortProf.response.encrypted,
            shortID.response.encrypted,
            1
          ));

          let newSubmod: Submodules[] = [];
          let subPerm = profInfo.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M02USPE')[0];
          this.submodulesAux.forEach(item => {
            let idSub = item.IDSUBMODULO;
            let sub = subPerm.children.filter(item2 => item2.id == idSub)[0];
            if(sub.access > 0){
              newSubmod.push(item);
            }
          });
          
          this.submodules = newSubmod;
        }catch(error: any){
          if(error.error == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else if(error.error.msg == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else{
            this.openSnackBar(error.error.msg);
          }
        }
      }
    })
  }

  async getSubmodules(){
    try{
      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = await this._encService.desencriptar(permissionsEnc!);
      let permissionsArr: Permissions = JSON.parse(permissionsDec);
      let permFun = permissionsArr.permissions.filter(item => item.id == 'S002V01M02USPE')[0];

      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.hasError = submodules.error;
      this.errorStr = submodules.msg;

      if(!this.hasError){
        submodules.response.forEach(item => {
          let idSub = item.IDSUBMODULO;
          let subm = permFun.children.filter(item2 => idSub == item2.id)[0];
          if(subm.access > 0){
            this.submodules.push(item);
          }
        });

        this.submodulesAux = submodules.response;
      }

      this.isLoading = false;
    }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 permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = await this._encService.desencriptar(permissionsEnc!);
      let permissionsArr: Permissions = JSON.parse(permissionsDec);

      let newFunct: SubmoduleFunctions[] = [];
      let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M02USPE')[0];
      let subPerm = modPerm.children.filter(item => item.id == submodule.IDSUBMODULO)[0];

      submoduleFunctions.response.forEach(item => {
        let idFunc = item.IDFUNCION;
        let func = subPerm.children.filter(item2 => item2.id == idFunc)[0];
        if(func.access > 0){
          newFunct.push(item);
        }
      });

      let dialogRef = this._dialog.open(SubmoduleFunctionsComponent, {
        width: '380px',
        data: {
          FUNCIONES: newFunct,
        },
      });
      
      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);
      }
    }
  }
}
