import { AlertComponent } from './../../../resources/dialogs/alert/alert.component';
import { FunctionsService } from './../../../../services/functions.service';
import { SCADA, SCADAList } from './../../../../interfaces/scada-list.interface';
import { EncService } from './../../../../services/enc/enc.service';
import { lastValueFrom } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';
import { RegisterScadaComponent } from './register-scada/register-scada.component';
import { MatDialog } from '@angular/material/dialog';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

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

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

  scadaList: SCADA[];
  displayedColumns: string[] =  ['ID', 'NOMBRE', 'ESTADO', 'USUARIO', 'FECHA', 'ACCIONES'];

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

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

  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 scadaList: SCADAList = await lastValueFrom(this._systemAdminService.getSCADAList(shortEnc.response.encrypted, 1));

      this.hasError = scadaList.error;
      if(this.hasError){
        this.errorStr = scadaList.msg;
        this.isLoading = false;
      }else{
        this.scadaList = scadaList.response;
        this.dataSource = new MatTableDataSource(this.scadaList);
        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.isLoading = false;
      this.hasError = true;
    }
  }

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

  openRegister(type: string, id?: number, name?: string){
    let dialogRef = this._matDialog.open(RegisterScadaComponent, {
      width: '480px',
      data: {
        type: type,
        id: id,
        name: name,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ""){
        let resArr = res.split('|');
        this.registerSCADA(resArr[0], resArr[1], id);
      }
    });
  }

  async registerSCADA(name: string, type: string, id?: number){
    try{
      let idUser = localStorage.getItem('idusuario');
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('scada_name', name);

      if(type == 'new'){
        await lastValueFrom(this._systemAdminService.registerSCADA(formData));
        this.openSnackBar('El SCADA se registró correctamente.');
      }else{
        let idSCADA = await this._encService.encriptar(`${id}`);
        formData.append('id_scada', idSCADA);
        
        await lastValueFrom(this._systemAdminService.updateSCADA(formData));
        this.openSnackBar('El SCADA se actualizó correctamente.');
      }

      this.getData();
    }catch(error: any){
      console.log(error);
      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);
      }
    }
  }

  getUserName(usrReg: string, usrMod?: string): string{
    if(usrMod != null){
      return usrMod!;
    }else{
      return usrReg;
    }
  }

  formateDate(dateReg: string, dateMod?: string): string{
    if(dateMod != null){
      return this._funcService.orderDate(dateMod);
    }else{
      return this._funcService.orderDate(dateReg);
    }
  }

  openDeleteAlert(id: number){
    let dialogRef = this._matDialog.open(AlertComponent, {
      data: {
        title: '¡Alerta!',
        icon: 'warning',
        description: '¿Está seguro de eliminar este SCADA?',
        description2: 'Esta acción no se puede revertir'
      }
    });

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

  async deleteSCADA(id: number){
    try{
      let idSCADA = await this._encService.encriptar(`${id}`);
      let idUser = localStorage.getItem('idusuario');
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('id_scada', idSCADA);
      formData.append('linea', '1');

      await lastValueFrom(this._systemAdminService.deleteSCADA(formData));
      this.openSnackBar('El SCADA se eliminó 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);
      }
    }
  }
}
