import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { ControlPanelsListItem, ControlPanelsListResponse } from '../../../interfaces/control-panel.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { ResourcesService } from '../../../services/resources.service';
import { ControlPanelService } from '../../../services/control-panel.service';
import { FunctionsService } from '../../../services/functions.service';
import { Router } from '@angular/router';
import { SocketService } from '../../../services/socket.service';
import { lastValueFrom } from 'rxjs';
import { NewPanelComponent } from './new-panel/new-panel.component';
import { PanelUsersComponent } from './panel-users/panel-users.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-graphic-interface-indicators',
    templateUrl: './graphic-interface-indicators.component.html',
    styleUrl: './graphic-interface-indicators.component.css',
    standalone: false
})
export class GraphicInterfaceIndicatorsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  public btnSmall: boolean = false;
  public txtBuscador:string;

  dataSource: MatTableDataSource<ControlPanelsListItem>;
  displayedColumns = ['ID', 'NOMBRE', 'ORIENTACION', 'USUARIOS', 'ESTADO', 'USUARIO', 'FECHA', 'ACCIONES'];

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

  constructor(
    private _dialog: MatDialog,
    private _encService: EncService,
    private _resourcesService: ResourcesService,
    private _controlPanelService: ControlPanelService,
    private _functionsService: FunctionsService,
    private _router: Router,
    private _socketService: SocketService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.txtBuscador = '';
    this.btnSmall = window.innerWidth <= 1405;
    
    this.dataSource = new MatTableDataSource();
  }
  
  ngOnInit(): void {
    this.getPanels();
  }

  async getPanels(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';

      let idUser = localStorage.getItem('idusuario')!;
      let controlPanels: ControlPanelsListResponse = await lastValueFrom(this._controlPanelService.getPanels(idUser, 1));

      this.hasError = controlPanels.error;
      this.errorStr = controlPanels.msg;

      if(!this.hasError){
        let controlPanelsArr: ControlPanelsListItem[] = [];
        for(const panel of controlPanels.response){
          panel.ID_PANEL = await this._encService.decrypt(panel.ID_PANEL);
          panel.FECREG = this._functionsService.orderDate(panel.FECREG);

          if(panel.FECMOD != null){
            panel.FECMOD = this._functionsService.orderDate(panel.FECMOD);
          }

          controlPanelsArr.push(panel);
        }

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

  public onResize():void {

  }

  applyFilter(event: any, type: string){
    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 openPanelForm(action: string, id: string | null){
    let dialogData = '';
    if(id != null){
      let elementFilt = this.dataSource.data.filter(item => item.ID_PANEL == id);
      if(elementFilt.length > 0){
        let dialogDataDec = `${elementFilt[0].ID_PANEL}|${elementFilt[0].NOMBRE_PANEL}|${elementFilt[0].ORIENTACION}`;
        dialogData = await this._encService.encrypt(dialogDataDec);
      }else{
        this._resourcesService.openSnackBar('El panel seleccionado no existe.');
        return;
      }
    }
    
    let dialogRef = this._dialog.open(NewPanelComponent, {
      width: '480px',
      maxWidth: '480px',
      disableClose: true,
      data: {
        action: action,
        data: dialogData,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.savePanel(res, action);
      }
    });
  }

  async savePanel(dataEnc: string, action: string){
    try{
      let dataDec = await this._encService.decrypt(dataEnc);
      let dataObj = JSON.parse(dataDec);
      
      let formData = new FormData();
      let idUser = localStorage.getItem('idusuario')!;

      formData.append('id_user', idUser);
      formData.append('linea', '1')
      formData.append('panel_name', dataObj.panelName);
      formData.append('orientation', dataObj.panelOrientation);

      if(action == 'new'){
        await lastValueFrom(this._controlPanelService.registerPanel(formData));
        this._resourcesService.openSnackBar('El panel de control se registró correctamente.');
      }else{
        let idPanelEnc = await this._encService.encrypt(dataObj.panelID);
        formData.append('id_panel', idPanelEnc);
        
        await lastValueFrom(this._controlPanelService.updatePanel(formData));
        this._resourcesService.openSnackBar('El panel de control se actualizó correctamente.');
      }

      this.getPanels();
    }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);
      }
    }
  }

  async openPanelElements(idPanel: string){
    let idPanelEnc = await this._encService.encrypt(idPanel);
    this._router.navigate(['sam/PCSA/MIIG/add-elements'], {
      queryParams: {
        data: idPanelEnc
      }
    });
  }

  async openControlPanelPreview(idPanel: string){
    let idPanelEnc = await this._encService.encrypt(idPanel);
    this._router.navigate(['sam/PCSA/MIIG/panel-preview'], {
      queryParams: {
        data: idPanelEnc,
      }
    });
  }

  async openPanelUsersDialog(idPanel: string){
    let panelFilt = this.dataSource.data.filter(item => item.ID_PANEL == idPanel);
    let idPanelEnc = await this._encService.encrypt(idPanel);

    if(panelFilt.length > 0){
      let panelStr = `${panelFilt[0].ID_PANEL}|${panelFilt[0].NOMBRE_PANEL}`;
      let panelEnc = await this._encService.encrypt(panelStr);
      let dialogRef = this._dialog.open(PanelUsersComponent, {
        width: '720px',
        maxWidth: '720px',
        disableClose: true,
        data: {
          panel: panelEnc,
        }
      });
      
      dialogRef.afterClosed().subscribe(res => {
        if(res != null && res != undefined && res != ''){
          this.updatePanelAssociations(res, idPanelEnc);
        }
      });
    }
  }

  async updatePanelAssociations(associations: string, idPanel: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();
      
      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_panel', idPanel);
      formData.append('associated_users', associations);

      await lastValueFrom(this._controlPanelService.updatePanelAssociations(formData));

      let socketMsg = `${associations}|${idPanel}`;
      let socketMsgEnc = await this._encService.encrypt(socketMsg);

      this._socketService.changePanelAssociations(socketMsgEnc);
      console.log(socketMsgEnc);

      this._resourcesService.openSnackBar('Los usuarios asociados se actualizaron correctamente.');
      this.getPanels();
    }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);
      }
    }
  }

  openDeleteAlert(idPanel: string){
    let panelFilt = this.dataSource.data.filter(item => item.ID_PANEL == idPanel);
    if(panelFilt.length > 0){
      let dialogRef = this._dialog.open(AlertComponent, {
        width: '480px',
        maxWidth: '480px',
        disableClose: true,
        data: {
          title: '¡Cuidado!',
          icon: 'warning',
          description: `¿Está seguro de querer eliminar el panel de control ${panelFilt[0].NOMBRE_PANEL} (${idPanel})?`,
          description2: 'Esta acción no se puede deshacer',
        }
      });

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

  private async deletePanel(idPanel: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idPanelEnc = await this._encService.encrypt(idPanel);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_panel', idPanelEnc);

      await lastValueFrom(this._controlPanelService.deletePanel(formData));

      this._resourcesService.openSnackBar('El panel se eliminó correctamente.');
      this.getPanels();
    }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);
      }
    }
  }
}
