import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { SCADA, SCADAList } from '../../../../interfaces/scada-list.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { FunctionsService } from '../../../../services/functions.service';
import { SocketService } from '../../../../services/socket.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { Router } from '@angular/router';
import { ResourcesService } from '../../../../services/resources.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { Permissions } from '../../../../interfaces/permissions.interface';
import { RegisterScadaComponent } from './register-scada/register-scada.component';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { EditScadaPasswordComponent } from './edit-scada-password/edit-scada-password.component';

@Component({
  selector: 'app-scada-admin',
  templateUrl: './scada-admin.component.html',
  styleUrl: './scada-admin.component.css',
  standalone: false
})
export class ScadaAdminComponent implements OnInit {
  btnSmall: boolean;
  txtBuscador: string;
  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;

  regEditSCADAEnabled: boolean;

  constructor(
    private _systemAdminService: SystemAdminService,
    private _matDialog: MatDialog,
    private _encService: EncService,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService, 
    private _router: Router,
    private _resourcesService: ResourcesService,
    private _functionsService: FunctionsService,
  ) {
    this.btnSmall = false;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource<any>();
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.scadaList = [];
    this.regEditSCADAEnabled = true;
  }

  ngOnInit(): void {
    this.getData();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('ERR_NPE000: Ocurrió un error inesperado.');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == 'S002V01M01ADSI');
            if(modPerm.length > 0){
              let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F06ASWA');
              if(funPerm.length > 0){
                let regEditSCADAEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02RESC');
                if(regEditSCADAEnabled.length > 0){
                  this.regEditSCADAEnabled = regEditSCADAEnabled[0].access > 0;
                }
              }
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('ERR_PAD001: Ocurrió un error inesperado.');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('ERR_PAD002: Ocurrió un error inesperado.');
        }else{
          this._resourcesService.openSnackBar(`ERR_PAD003: ${error.error.msg}`);
        }
      }
    });
  }

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

      let idUser = localStorage.getItem('idusuario')!;
      let scadaList: SCADAList = await lastValueFrom(this._systemAdminService.getSCADAList(idUser, 1));

      this.hasError = scadaList.error;
      this.errorStr = scadaList.msg;
      if(!this.hasError){
        this.scadaList = scadaList.response;
        this.dataSource = new MatTableDataSource(this.scadaList);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;

        let permissionsEnc = localStorage.getItem('permisos');
        let permissionsDec = await this._encService.decrypt(permissionsEnc!);
        let permissionsArr: Permissions = JSON.parse(permissionsDec);

        let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
        let funPerm = modPerm.children.filter(item => item.id == 'S002V01F06ASWA')[0];

        this.regEditSCADAEnabled = funPerm.children.filter(item => item.id == 'S002V01P02RESC')[0].access > 0;
      }
      
      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;
    }
  }
  
  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 openRegister(type: string, id?: number, name?: string){
    let idEnc = id == undefined ? id : await this._encService.encrypt(`${id}`);
    let dialogRef = this._matDialog.open(RegisterScadaComponent, {
      width: '480px',
      minWidth: '480px',
      data: {
        type: type,
        id: idEnc,
        name: name,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ""){
        this.registerSCADA(res, type, idEnc);
      }
    });
  }

  async registerSCADA(data: string, type: string, id?: number | string){
    try{
      let dataDec = await this._encService.decrypt(data);
      let dataObj = JSON.parse(dataDec);
      let passEnc = await this._encService.encrypt(dataObj.scadaPassControl);
      
      let idUser = localStorage.getItem('idusuario');
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('scada_name', dataObj.scadaNameControl);
      formData.append('scada_pass', passEnc);

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

      this.getData();
    }catch(error: any){
      console.log(error);
      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 openEditPassword(idSCADA: number){
    let idSCADAEnc = await this._encService.encrypt(`${idSCADA}`);
    let dialogRef = this._matDialog.open(EditScadaPasswordComponent, {
      width: '480px',
      minWidth: '480px',
      data: {
        id: idSCADAEnc
      }
    });

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

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

      let lastPasswordEnc = await this._encService.encrypt(dataObj.lastPaswordControl);
      let newPasswordEnc = await this._encService.encrypt(dataObj.newPasswordControl);

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('last_password', lastPasswordEnc);
      formData.append('new_password', newPasswordEnc);
      formData.append('id_scada', idSCADA);

      await lastValueFrom(this._systemAdminService.updateSCADAPassword(formData));

      this._resourcesService.openSnackBar('La contraseña del SCADA se actualizó correctamente.');
      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);
      }
    }
  }

  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._functionsService.orderDate(dateMod)!;
    }else{
      return this._functionsService.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.encrypt(`${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._resourcesService.openSnackBar('El SCADA se eliminó correctamente.');

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