import { Component, OnInit } from '@angular/core';
import { Submodules, SubmodulesResponse } from '../../interfaces/submodules.interface';
import { EncService } from '../../services/enc.service';
import { ModulesService } from '../../services/modules.service';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { Permissions, PermissionsInterface } from '../../interfaces/permissions.interface';
import { lastValueFrom } from 'rxjs';
import { SpecialtiesManagementComponent } from './specialties-management/specialties-management.component';
import { SubmoduleFunctionsComponent } from '../template/menu-item/submodule-functions/submodule-functions.component';

@Component({
    selector: 'app-personal-management',
    templateUrl: './personal-management.component.html',
    styleUrl: './personal-management.component.css',
    standalone: false
})
export class PersonalManagementComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  submodules: Submodules[];
  submodulesAux: Submodules[];

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

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

  openOrganization(){
    this._router.navigate(['sam/organization'])
  }

  async getSubmodules(){
    try{
      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = '';
      if(permissionsEnc == '' || permissionsEnc == undefined || permissionsEnc == null){
        permissionsDec = '[]';
      }else{
        permissionsDec = await this._encService.decrypt(permissionsEnc!);
      }

      let permissionsArr: Permissions = JSON.parse(permissionsDec);
      let permFun: PermissionsInterface[] = [];
      if(permissionsArr.permissions == undefined){
        permFun = [];
      }else{
        permFun = permissionsArr.permissions.filter(item => item.id == 'S002V01M11GPRS');
      }
      
      let moduleEnc = await this._encService.encrypt('S002V01M11GPRS');
      let idEnc = localStorage.getItem('idusuario')!;
      let submodules: SubmodulesResponse = await lastValueFrom(this._modulesService.getSubmodules(
        moduleEnc,
        idEnc, 
        1
      ));

      this.hasError = submodules.error;
      this.errorStr = submodules.msg;

      if(!this.hasError){
        
        for(const submodule of submodules.response){
          let idSub = await this._encService.decrypt(submodule.IDSUBMODULO);
          submodule.IDSUBMODULO = idSub;

          if(permFun.length > 0){
            let subm = permFun[0].children.filter(item2 => idSub == item2.id);
            if(subm.length > 0){
              if(subm[0].access > 0){
                this.submodules.push(submodule);
              }
            }
          }
        }

        this.submodulesAux = submodules.response;
      }

      this.isLoading = false;
    }catch(error: any){
      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;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  openSpecialtiesManagement(){
    this._dialog.open(SpecialtiesManagementComponent, {
      disableClose: true,
      width: '960px',
      maxWidth: '960px',
    });
  }

  openMenu(submodule: Submodules){
    let dialogRef = this._dialog.open(SubmoduleFunctionsComponent, {
      width: '560px',
      maxWidth: '560px',
      data: {
        module: 'S002V01M11GPRS',
        submodule: submodule.IDSUBMODULO,
      },
    });

    // GPRS/GESU/ADCO
    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/GPRS/${idSub}/${idFunc}`]);
      }
    });
  }
}
