import { AsignWebServiceComponent } from './asign-web-service/asign-web-service.component';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatSort } from '@angular/material/sort';
import { MatPaginator } from '@angular/material/paginator';
import { RoutedTokensRespose } from './../../../../interfaces/routed-tokens.interface';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { lastValueFrom } from 'rxjs';
import { EncService } from './../../../../services/enc/enc.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

@Component({
  selector: 'app-scada-web-service-link',
  templateUrl: './scada-web-service-link.component.html',
  styleUrls: ['./scada-web-service-link.component.css']
})
export class ScadaWebServiceLinkComponent implements OnInit {
  public btnSmall: boolean;
  public txtBuscador: string;
  public dataSource: MatTableDataSource<any>;

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

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

  displayedColumns: string[] =  ['SCADA', 'DESCRIPCIONSC', 'SERVICIOWEB', 'DESCRIPCIONSW', 'ESTADO', 'ACCIONES'];

  constructor(
    private _encService: EncService,
    private _sysAdminService: SystemAdminService,
    private _snackBar: MatSnackBar,
    private _dialog: MatDialog,
  ) { 
    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 routedTokens: RoutedTokensRespose = await lastValueFrom(this._sysAdminService.getRoutedTokens(shortEnc.response.encrypted, 1));

      this.dataSource = new MatTableDataSource(routedTokens.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;
      }
    }
  }

  async changeTokenAccess(actualState: string, tokenKey: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let newState = actualState == 'Activo' ? 'Inactivo' : 'Activo';
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('estado', newState);
      formData.append('key', tokenKey);
      
      await lastValueFrom(this._sysAdminService.changeTokenAccess(formData));

      this.openSnackBar('El estado del token se actualizó correctemente.');
      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,
    });
  }

  openWebServiceDialog(key: string, service: string, desc: string){
    let serviceArr = service.split('(').reverse();
    let serviceStr = serviceArr[0].replace(")", "");
    
    let dialogRef = this._dialog.open(AsignWebServiceComponent, {
      width: '480px',
      data: {
        key: key,
        webService: serviceStr,
        description: desc,
      }
    });

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