import { Permissions } from './../../../interfaces/permissions.interface';
import { Component, OnInit } from '@angular/core';
import { EncService } from 'src/app/services/enc/enc.service';
import { SocketService } from 'src/app/services/socket.service';
import { lastValueFrom } from 'rxjs';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { Router } from '@angular/router';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-web-services-admin',
  templateUrl: './web-services-admin.component.html',
  styleUrls: ['./web-services-admin.component.css']
})
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 _usersProfilesSevice: UsersProfilesService,
    private _router: Router,
    private _snackBar: MatSnackBar,
  ) { 
    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) => {
      let shortID = await lastValueFrom(this._encService.shortEncrypt(localStorage.getItem('idusuario')!));
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.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._usersProfilesSevice.getProfile(
            shortProf.response.encrypted,
            shortID.response.encrypted,
            1
          ));

          let modPerm = profInfo.response.PERMISOS.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;
        }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);
          }
        }
      }
    });
  }

  async initPermissions(){
    try{
      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = await this._encService.desencriptar(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;
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, 'Cerrar', {
      duration: 5000
    });
  }
}
