import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { EncService } from '../../../../services/enc.service';
import { SystemAdminService } from '../../../../services/system-admin.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 { GeneratedTokensResponse } from '../../../../interfaces/generated-tokens.interface';
import { Permissions } from '../../../../interfaces/permissions.interface';
import { TokenGeneratorComponent } from './token-generator/token-generator.component';
import { TokenViewerComponent } from './token-viewer/token-viewer.component';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-tokens-admin',
    templateUrl: './tokens-admin.component.html',
    styleUrl: './tokens-admin.component.css',
    standalone: false
})
export class TokensAdminComponent implements OnInit {
  btnSmall: boolean;
  txtBuscador: string;
  dataSource: MatTableDataSource<any>;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  displayedColumns: string[] =  ['NOMBRE', 'DESCRIPCION', 'ESTATUS', 'USUARIO', 'FECHA', 'ACCIONES'];

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  generateTokenEnabled: boolean;

  constructor(
    private _dialog: MatDialog,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService, 
    private _router: Router,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.btnSmall = false;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource<any>();
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.generateTokenEnabled = true;
  }

  ngOnInit(): void {
    this.getData();
    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 generateTokenEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P04GETO');
                if(generateTokenEnabled.length > 0){
                  this.generateTokenEnabled = generateTokenEnabled[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 getData(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      
      let idUser = localStorage.getItem('idusuario')!;
      let tokens: GeneratedTokensResponse = await lastValueFrom(this._sysAdminService.getGeneratedTokens(idUser, 1));

      this.dataSource = new MatTableDataSource(tokens.response);
      this.dataSource.paginator = this.paginator!;
      this.dataSource.sort = this.sort!;

      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.generateTokenEnabled = funPerm.children.filter(item => item.id == 'S002V01P04GETO')[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;
    }
  }
  
  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }
  
  public applyFilter(event: any, type: string):void {
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  generateToken(){
    let dialogRef = this._dialog.open(TokenGeneratorComponent, {
      width: '480px',
      maxWidth: '480px',
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != "" && res != null && res != undefined){
        this.openToken(res);
      }
    });
  }

  async openToken(token: string){
    let tokenEnc = await this._encService.encrypt(token);
    let dialogRef = this._dialog.open(TokenViewerComponent, {
      width: '720px',
      maxWidth: '720px',
      data: {
        token: tokenEnc,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      this.getData();
    });
  }

  getUser(usre: string, usmo?: string): string{
    if(usmo == null || usmo == undefined || usmo == ""){
      return usre;
    }else{
      return usmo;
    }
  }

  getDate(fere: string, femo?: string): string{
    if(femo == null || femo == undefined || femo == ""){
      return this.orderDate(fere);
    }else{
      return this.orderDate(femo);
    }
  }

  orderDate(date: string): string{
    return this._functionsService.orderDate(date)!;
  }

  alertRevoke(token: string){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '480px',
      maxWidth: '480px',
      data: {
        title: 'Alerta',
        icon: 'warning',
        description: '¿Está seguro de realizar esta acción?',
        description2: 'Esta acción no se puede deshacer. Al ejecutar esta acción el SCADA relacionado no podrá comunicarse con el servicio web relacionado.'
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        this.revokeToken(token);
      }
    });
  }

  async revokeToken(idScada: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('token_key', idScada);
      formData.append('linea', '1');

      await lastValueFrom(this._sysAdminService.revokeToken(formData));
      
      this._resourcesService.openSnackBar('El token fue revocado correctamente');
      this.getData();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
