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 { SubmoduleFunctionsComponent } from '../template/menu-item/submodule-functions/submodule-functions.component';
import { ProfileInterface } from '../../interfaces/profile.interface';
import { UserConsultResponse } from '../../interfaces/user.interface';
import { SocketService } from '../../services/socket.service';
import { UsersProfilesService } from '../../services/users-profiles.service';
import { ResourcesService } from '../../services/resources.service';
import { FunctionsService } from '../../services/functions.service';

const ID_MODULE = "S002V01M10GMPR";
@Component({
    selector: 'app-preventive-maintenance',
    templateUrl: './preventive-maintenance.component.html',
    styleUrl: './preventive-maintenance.component.css',
    standalone: false
})
export class PreventiveMaintenanceComponent 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,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) { 
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.submodules = [];
    this.submodulesAux = [];
  }

  ngOnInit(): void {
    this.getSubmodules();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('ERR_NPE000: Ocurrió un error inesperado.');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == ID_MODULE);
            if(modPerm.length > 0){
              let newSubmod: Submodules[] = [];
              for(let item of this.submodulesAux){
                let idSub = item.IDSUBMODULO;
                let sub = modPerm[0].children.filter(item2 => item2.id == idSub);

                if(sub.length > 0){
                  if(sub[0].access > 0){
                    newSubmod.push(item);
                  }
                }
              }

              this.submodules = newSubmod;
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('ERR_PAD001: Ocurrió un error inesperado.');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('ERR_PAD002: Ocurrió un error inesperado.');
        }else{
          this._resourcesService.openSnackBar(`ERR_PAD003: ${error.error.msg}`);
        }
      }
    });

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  }

  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 == 'S002V01M10GMPR');
      }

      let moduleEnc = await this._encService.encrypt('S002V01M10GMPR');
      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;
    }
  }

  openMenu(submodule: Submodules){
    let dialogRef = this._dialog.open(SubmoduleFunctionsComponent, {
      width: '560px',
      maxWidth: '560px',
      data: {
        module: 'S002V01M10GMPR',
        submodule: submodule.IDSUBMODULO,
      },
    });
    
    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/GMPR/${idSub}/${idFunc}`]);
      }
    });
  }
}
