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

@Component({
    selector: 'app-control-panel',
    templateUrl: './control-panel.component.html',
    styleUrl: './control-panel.component.css',
    standalone: false
})
export class ControlPanelComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  
  functions: ModuleFunction[];
  functionsAux: ModuleFunction[];

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

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

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

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

      let modEnc = await this._encService.encrypt('S002V01M14PCSA');
      let idEnc = localStorage.getItem('idusuario')!;

      let functions: ModuleFunctionsResponse = await lastValueFrom(this._modulesService.getModuleFunctions(
        modEnc, 
        idEnc, 
        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/PCSA/${route}`]);
  }
}
