import { Component, OnInit } from '@angular/core';
import { EncService } from '../../../services/enc.service';
import { SocketService } from '../../../services/socket.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { Router } from '@angular/router';
import { ResourcesService } from '../../../services/resources.service';
import { FunctionsService } from '../../../services/functions.service';
import { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { Permissions } from '../../../interfaces/permissions.interface';

@Component({
    selector: 'app-web-services-admin',
    templateUrl: './web-services-admin.component.html',
    styleUrl: './web-services-admin.component.css',
    standalone: false
})
export class WebServicesAdminComponent implements OnInit {
  scadaAdminEnabled: boolean;
  tokensAdminEnabled: boolean;
  scadaWebserviceLinkEnabled: boolean;
  webServicesAdminEnabled: boolean;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  constructor(
    private _encService: EncService,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService,
    private _router: Router,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.scadaAdminEnabled = true;
    this.tokensAdminEnabled = true;
    this.scadaWebserviceLinkEnabled = true;
    this.webServicesAdminEnabled = true;

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

  ngOnInit(): void {
    this.initPermissions();
    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 == 'S002V01M01ADSI');
            if(modPerm.length > 0){
              let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F06ASWA');
              if(funPerm.length > 0){
                let scadaAdminEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01ADSC');
                if(scadaAdminEnabled.length > 0){
                  this.scadaAdminEnabled = scadaAdminEnabled[0].access > 0;
                }

                let tokensAdminEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P03ADTO');
                if(tokensAdminEnabled.length > 0){
                  this.tokensAdminEnabled = tokensAdminEnabled[0].access > 0;
                }

                let scadaWebserviceLinkEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P05ESSW');
                if(scadaWebserviceLinkEnabled.length > 0){
                  this.scadaWebserviceLinkEnabled = scadaWebserviceLinkEnabled[0].access > 0;
                }

                let webServicesAdminEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P06LSWE');
                if(webServicesAdminEnabled.length > 0){
                  this.webServicesAdminEnabled = webServicesAdminEnabled[0].access > 0;
                }
              }
            }
          }
        }
      }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}`);
        }
      }
    });
  }

  async initPermissions(){
    try{
      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = await this._encService.decrypt(permissionsEnc!);
      let permissionsArr: Permissions = JSON.parse(permissionsDec);

      let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
      let funPerm = modPerm.children.filter(item => item.id == 'S002V01F06ASWA')[0];

      this.scadaAdminEnabled = funPerm.children.filter(item => item.id == 'S002V01P01ADSC')[0].access > 0;
      this.tokensAdminEnabled = funPerm.children.filter(item => item.id == 'S002V01P03ADTO')[0].access > 0;
      this.scadaWebserviceLinkEnabled = funPerm.children.filter(item => item.id == 'S002V01P05ESSW')[0].access > 0;
      this.webServicesAdminEnabled = funPerm.children.filter(item => item.id == 'S002V01P06LSWE')[0].access > 0;

      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;
    }
  }
}
