import { AlertComponent } from './../../../resources/dialogs/alert/alert.component';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatSort } from '@angular/material/sort';
import { MatPaginator } from '@angular/material/paginator';
import { FunctionsService } from './../../../../services/functions.service';
import { GeneratedTokensResponse } from './../../../../interfaces/generated-tokens.interface';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { lastValueFrom } from 'rxjs';
import { EncService } from 'src/app/services/enc/enc.service';
import { TokenWiewerComponent } from './../scada-admin/token-wiewer/token-wiewer.component';
import { TokenGeneratorComponent } from './token-generator/token-generator.component';
import { MatDialog } from '@angular/material/dialog';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

@Component({
  selector: 'app-tokens-admin',
  templateUrl: './tokens-admin.component.html',
  styleUrls: ['./tokens-admin.component.css']
})
export class TokensAdminComponent implements OnInit {
  public btnSmall: boolean;
  public txtBuscador: string;
  public 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;

  constructor(
    private _dialog: MatDialog,
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _funcService: FunctionsService,
    private _snackBar: MatSnackBar,
  ) { 
    this.btnSmall = false;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource<any>();
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
  }

  ngOnInit(): void {
    this.getData();
  }
  
  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();
    }
  }

  async getData(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      
      let idUser = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));
      let tokens: GeneratedTokensResponse = await lastValueFrom(this._sysAdminService.getGeneratedTokens(shortEnc.response.encrypted, 1));

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

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

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

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

  async openToken(token: string){
    let tokenEnc = await this._encService.encriptar(token);
    let dialogRef = this._dialog.open(TokenWiewerComponent, {
      width: '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._funcService.orderDate(date);
  }

  alertRevoke(token: string){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '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.openSnackBar('El token fue revocado correctamente');
      this.getData();
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    })
  }
}
