import { Component, OnInit, ViewChild } from '@angular/core';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatorsListItem, ActivatorsListResponse } from '../../../interfaces/counters-activators.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { CountersActivatorsService } from '../../../services/counters-activators.service';
import { EncService } from '../../../services/enc.service';
import { SystemAdminService } from '../../../services/system-admin.service';
import { Router } from '@angular/router';
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 { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { Permissions } from '../../../interfaces/permissions.interface';
import { ActivatorDetailsComponent } from './activator-details/activator-details.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

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

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

  orderPriorities: PriorityInterface[];

  dataSource: MatTableDataSource<ActivatorsListItem>;
  displayedColumns = ['IDAC', 'PRIO', 'TIPO', 'IDCO', 'ESTADO', 'ACCIONES'];

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

  activatorsConsultEnabled: boolean;
  registerActivatorEnabled: boolean;
  deleteActivatorEnabled: boolean;

  constructor(
    private _countersActivatorsService: CountersActivatorsService,
    private _encService: EncService,
    private _systemAdminService: SystemAdminService,
    private _router: Router,
    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.orderPriorities = [];
    this.dataSource = new MatTableDataSource();

    this.activatorsConsultEnabled = true;
    this.registerActivatorEnabled = true;
    this.deleteActivatorEnabled = true;
  }

  ngOnInit(): void {
    this.getPriorities();
    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 == 'S002V01S02ACTI');
              if(subPerm.length > 0){
                let funPerm = subPerm[0].children.filter(item => item.id == 'S002V01F01GEAC');
                if(funPerm.length > 0){
                  let activatorsConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COAC');
                  if(activatorsConsultEnabled.length > 0){
                    this.activatorsConsultEnabled = activatorsConsultEnabled[0].access > 0;
                  }
  
                  let registerActivatorEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02REAC');
                  if(registerActivatorEnabled.length > 0){
                    this.registerActivatorEnabled = registerActivatorEnabled[0].access > 0;
                  }
                }
  
                let deleteActivatorEnabled = subPerm[0].children.filter(item => item.id == 'S002V01F02ELAC');
                if(deleteActivatorEnabled.length > 0){
                  this.deleteActivatorEnabled = deleteActivatorEnabled[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 getPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._systemAdminService.getOrderPriorities(idUser, 1));

      if(priorities.error){
        this.hasError = true;
        this.errorStr = priorities.msg;
        this.isLoading = false;
      }else{
        this.orderPriorities = priorities.response.order_priorities;
        this.getActivators();
      }
    }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;
    }
  }

  async getActivators(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';
      
      let idUser = localStorage.getItem('idusuario')!;
      let activators: ActivatorsListResponse = await lastValueFrom(this._countersActivatorsService.activatorConsult(idUser, 1));

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

      if(!this.hasError){
        let activatorsArr: ActivatorsListItem[] = [];
        for(const activator of activators.response){
          activator.ID_ACTIVADOR = await this._encService.decrypt(activator.ID_ACTIVADOR);
          activator.ID_CONTADOR = await this._encService.decrypt(activator.ID_CONTADOR);

          activatorsArr.push(activator);
        }

        this.dataSource = new MatTableDataSource(activatorsArr);
        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 == 'S002V01S02ACTI');
            if(subPerm.length > 0){
              let funPerm = subPerm[0].children.filter(item => item.id == 'S002V01F01GEAC');
              if(funPerm.length > 0){
                let activatorsConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COAC');
                if(activatorsConsultEnabled.length > 0){
                  this.activatorsConsultEnabled = activatorsConsultEnabled[0].access > 0;
                }

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

              let deleteActivatorEnabled = subPerm[0].children.filter(item => item.id == 'S002V01F02ELAC');
              if(deleteActivatorEnabled.length > 0){
                this.deleteActivatorEnabled = deleteActivatorEnabled[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 openActivatorForm(type: string, idActivator: string = '-'){
    let idActivatorEnc = await this._encService.encrypt(idActivator);
    this._router.navigate([`sam/COAC/ACTI/GEAC/${type}`], {
      queryParams: {
        idActivator: idActivatorEnc
      }
    })
  }

  getFontColor(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "rgb(0, 0, 0)";
    
    let priority = priorityFiltered[0];
    return priority.color;
  }

  getPriorityStr(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "-";
    
    let priority = priorityFiltered[0];
    return priority.label;
  }

  async openDetailsDialog(idActivator: string){
    let idActivatorEnc = await this._encService.encrypt(idActivator);
    let dialogRef = this._dialog.open(ActivatorDetailsComponent, {
      width: '480px',
      maxWidth: '480px',
      data: {
        idActivator: idActivatorEnc,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      console.log(res);
    });
  }

  openDeleteAlert(idActivator: string){
    let res = this._dialog.open(AlertComponent, {
      width: '420px',
      maxWidth: '420px',
      data: {
        title: '¡Cuidado!',
        icon: 'warning',
        description: `¿Está seguro de eliminar el activador #${idActivator}?`,
        description2: 'Esta acción no se puede deshacer.'
      }
    });

    res.afterClosed().subscribe(res => {
      if(res == true){
        this.deleteActivator(idActivator);
      }
    })
  }

  private async deleteActivator(idActivator: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idActivatorEnc = await this._encService.encrypt(idActivator);

      await lastValueFrom(this._countersActivatorsService.activatorDelete({
        id_user: idUser,
        linea: 1,
        id_activator: idActivatorEnc
      }));

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