import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { CountersListItem, CountersListResponse } from '../../../interfaces/counters-activators.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { Router } from '@angular/router';
import { EncService } from '../../../services/enc.service';
import { CountersActivatorsService } from '../../../services/counters-activators.service';
import { MatDialog } from '@angular/material/dialog';
import { ResourcesService } from '../../../services/resources.service';
import { SocketService } from '../../../services/socket.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { FunctionsService } from '../../../services/functions.service';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { lastValueFrom } from 'rxjs';
import { UserConsultResponse } from '../../../interfaces/user.interface';
import { Permissions } from '../../../interfaces/permissions.interface';
import { CounterDetailsComponent } from './counter-details/counter-details.component';
import { RelatedCountersComponent } from './related-counters/related-counters.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

const ID_MODULE = "S002V01M06COAC";
@Component({
    selector: 'app-counters-management',
    templateUrl: './counters-management.component.html',
    styleUrl: './counters-management.component.css',
    standalone: false
})
export class CountersManagementComponent implements OnInit {
  public txtBuscador:string;

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

  dataSource: MatTableDataSource<CountersListItem>;
  displayedColumns = ['ID', 'SCADA', 'EQUIPAMIENTO', 'ACCIONES'];

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

  countersConsultEnabled: boolean;
  registerCounterEnabled: boolean;
  deleteCounterEnabled: boolean;

  constructor(
    private _router: Router,
    private _encService: EncService,
    private _countersActivatorsService: CountersActivatorsService,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.txtBuscador = '';

    this.btnSmall = window.innerWidth <= 1405;
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";

    this.dataSource = new MatTableDataSource();

    this.countersConsultEnabled = true;
    this.registerCounterEnabled = true;
    this.deleteCounterEnabled = true;
  }

  ngOnInit(): void {
    this.getCounters();
    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 == 'S002V01M06COAC');
            if(modPerm.length > 0){
              let subPerm = modPerm[0].children.filter(item => item.id == 'S002V01S01CONT');
              if(subPerm.length > 0){
                let funPerm = subPerm[0].children.filter(item => item.id == 'S002V01F01GECO');
                if(funPerm.length > 0){
                  let countersConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COCO');
                  if(countersConsultEnabled.length > 0){
                    this.countersConsultEnabled = countersConsultEnabled[0].access > 0;
                  }

                  let registerCounterEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02RECO');
                  if(registerCounterEnabled.length > 0){
                    this.registerCounterEnabled = registerCounterEnabled[0].access > 0;
                  }
                }

                let deleteCounterEnabled = subPerm[0].children.filter(item => item.id == 'S002V01F02ELCO');
                if(deleteCounterEnabled.length > 0){
                  this.deleteCounterEnabled = deleteCounterEnabled[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}`);
        }
      }
    });

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  }

  async getCounters(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      
      let idUser = localStorage.getItem('idusuario')!;
      let counters: CountersListResponse = await lastValueFrom(this._countersActivatorsService.counterConsult(idUser, 1));

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

      if(!this.hasError){
        let countersArr: CountersListItem[] = [];
        for(const counter of counters.response){
          let idCountDec = await this._encService.decrypt(counter.ID_CONTADOR);
          counter.ID_CONTADOR = idCountDec;

          let idSCADADec = await this._encService.decrypt(counter.ID_SCADA);
          counter.SCADA = `${counter.SCADA} (${idSCADADec})`;

          let codeDec = await this._encService.decrypt(counter.CODIGO_EQUIPAMIENTO);
          counter.TIPO_EQUIPAMIENTO = `${codeDec} - ${counter.TIPO_EQUIPAMIENTO}`;

          let idEquipmentDec = await this._encService.decrypt(counter.ID_EQUIPAMIENTO);
          counter.MODELO_EQUIPAMIENTO = `${counter.MODELO_EQUIPAMIENTO} (${idEquipmentDec})`;
          
          if(counter.ESTADO == 'Activo'){
            countersArr.push(counter);
          }
        }

        this.dataSource = new MatTableDataSource(countersArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;

        let permissionsEnc = localStorage.getItem('permisos');
        let permissionsDec = '';
        if(permissionsEnc == '' || permissionsEnc == undefined || permissionsEnc == null){
          permissionsDec = '[]';
        }else{
          permissionsDec = await this._encService.decrypt(permissionsEnc!);
        }

        let permissionsArr: Permissions = JSON.parse(permissionsDec);
        if(permissionsArr.permissions != undefined){
          let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M06COAC');
          if(modPerm.length > 0){
            let subPerm = modPerm[0].children.filter(item => item.id == 'S002V01S01CONT');
            if(subPerm.length > 0){
              let funPerm = subPerm[0].children.filter(item => item.id == 'S002V01F01GECO');
              if(funPerm.length > 0){
                let countersConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COCO');
                if(countersConsultEnabled.length > 0){
                  this.countersConsultEnabled = countersConsultEnabled[0].access > 0;
                }

                let registerCounterEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02RECO');
                if(registerCounterEnabled.length > 0){
                  this.registerCounterEnabled = registerCounterEnabled[0].access > 0;
                }
              }

              let deleteCounterEnabled = subPerm[0].children.filter(item => item.id == 'S002V01F02ELCO');
              if(deleteCounterEnabled.length > 0){
                this.deleteCounterEnabled = deleteCounterEnabled[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.hasError = true;
      this.isLoading = false;
    }
  }

  public onResize(): void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  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 openCounterForm(type: string, idCounter: string = '-'){
    let idCounterEnc = await this._encService.encrypt(idCounter);
    this._router.navigate([`sam/COAC/CONT/GECO/${type}`], {
      queryParams: {
        idCounter: idCounterEnc
      }
    })
  }

  async openCounterDetails(idCounter: string){
    let counterFilt = this.dataSource.data.filter(item => item.ID_CONTADOR == idCounter);
    if(counterFilt.length < 1){
      this._resourcesService.openSnackBar(`El contador #${idCounter} no existe.`);
      return;
    }
    
    let idCounterEnc = await this._encService.encrypt(idCounter);
    this._dialog.open(CounterDetailsComponent, {
      width: '540px',
      maxWidth: '540px',
      data: {
        idCounter: idCounterEnc,
        includeActivator: counterFilt[0].TIENE_ACTIVADOR,
        idActivator: counterFilt[0].ACTIVADOR,
      }
    })
  }

  async openRelatedCounters(idCounter: string){
    let idCounterEnc = await this._encService.encrypt(idCounter);
    let dialogRef = this._dialog.open(RelatedCountersComponent, {
      width: '840px',
      data: {
        idCounter: idCounterEnc
      }
    });

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

  private async saveRelatedCounters(idCounter: string, dataEnc: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let dataDec = await this._encService.decrypt(dataEnc);
      let idCounterEnc = await this._encService.encrypt(idCounter);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_counter', idCounterEnc);
      formData.append('related_counters', dataDec);

      await lastValueFrom(this._countersActivatorsService.relateCounters(formData));

      this._resourcesService.openSnackBar('La vinculación del contador se realizó correctamente.');
      this.getCounters();
    }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 openConfirmDialog(idCounter: string){
    let idCounterEnc = await this._encService.encrypt(idCounter);
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '420px',
      maxWidth: '420px',
      data: {
        title: 'Confirmación',
        icon: 'warning',
        description: '¿Está seguro de continuar con la eliminación del registro?',
        description2: 'Esta acción no se puede deshacer'
      }
    });

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

  private async deleteCounter(idCounterEnc: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_counter', idCounterEnc);

      await lastValueFrom(this._countersActivatorsService.counterDelete(formData));

      this._resourcesService.openSnackBar('El contador se eliminó correctamente.');
      this.getCounters();
    }catch(error: any){
      if(error.error.msg == 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('Ocurrió un error inesperado.');
      }
    }
  }
}
