import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { MatDialog } from '@angular/material/dialog';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { ResourcesService } from '../../../../services/resources.service';
import { lastValueFrom } from 'rxjs';
import { RoutedTokensRespose } from '../../../../interfaces/routed-tokens.interface';
import { AsignWebServiceComponent } from './asign-web-service/asign-web-service.component';

@Component({
    selector: 'app-scada-web-service-link',
    templateUrl: './scada-web-service-link.component.html',
    styleUrl: './scada-web-service-link.component.css',
    standalone: false
})
export class ScadaWebServiceLinkComponent implements OnInit {
  btnSmall: boolean;
  txtBuscador: string;
  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 _sysAdminService: SystemAdminService,
    private _dialog: MatDialog,
    private _matIconRegistry: MatIconRegistry,
    private _domSanitizer: DomSanitizer,
    private _resourcesService: ResourcesService,
  ) {
    this._matIconRegistry.addSvgIcon(
      'sw',
      this._domSanitizer.bypassSecurityTrustResourceUrl(window.location.origin + "/assets/img/custom_icons/sw.svg")
    );

    this.btnSmall = window.innerWidth <= 1784;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource<any>();

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

  ngOnInit(): void {
    this.getData();
  }

  async getData(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";

      let idUser = localStorage.getItem('idusuario')!;
      let routedTokens: RoutedTokensRespose = await lastValueFrom(this._sysAdminService.getRoutedTokens(idUser, 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;
      }
    }
  }
  
  public onResize():void {
    this.btnSmall = window.innerWidth <= 1784;
  }
  
  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 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._resourcesService.openSnackBar('El estado del token se actualizó correctemente.');
      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);
      }
    }
  }

  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',
      maxWidth: '480px',
      data: {
        key: key,
        webService: serviceStr,
        description: desc,
      }
    });

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