import { MatSnackBar } from '@angular/material/snack-bar';
import { SocketService } from './../../services/socket.service';
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';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';

@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[];
  functionsAux: ModuleFunction[];

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

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

  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 newFunct: ModuleFunction[] = [];
          let funcPerm = profInfo.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
          this.functionsAux.forEach(item => {
            let idFunc = item.IDFUNCION;
            let func = funcPerm.children.filter(item2 => item2.id == idFunc)[0];
            if(func.access > 0){
              newFunct.push(item);
            }
          });
          
          this.functions = newFunct;
        }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);
          }
        }
      }
    })
  }

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

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

      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;
      this.errorStr = functions.msg;

      if(!this.hasError){
        functions.response.forEach(item => {
          let idFunc = item.IDFUNCION;
          let func = permMod.children.filter(item2 => idFunc == item2.id)[0];
          if(func.access > 0){
            this.functions.push(item);
          }
        });

        this.functionsAux = 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);
  }
}
