import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { Router } from '@angular/router';
import { EncService } from '../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { FunctionsService } from '../../../services/functions.service';
import { SocketService } from '../../../services/socket.service';
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 { ProfilesResponse } from '../../../interfaces/profiles.interface';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

const ID_MODULE = "S002V01M02USPE";
interface TableInfo{
  ID: string,
  NOMBRE: string,
  FECHA: string,
  ESTADO: string 
}
@Component({
    selector: 'app-profiles-admin',
    templateUrl: './profiles-admin.component.html',
    styleUrl: './profiles-admin.component.css',
    standalone: false
})
export class ProfilesAdminComponent implements OnInit {
  public btnSmall: boolean = false;
  public txtBuscador:string;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  profiles: Array<TableInfo>;
  searching: boolean;

  displayedColumns: string[] =  ['ID', 'NOMBRE', 'FECHA', 'ESTATUS', 'ACCIONES'];
  dataSource?: MatTableDataSource<TableInfo>;

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

  profilesHistoryEnabled: boolean;
  regEditProfileEnabled: boolean;
  viewPermissionsEnabled: boolean;

  constructor(
    private _usersProfilesService: UsersProfilesService, 
    private _router: Router, 
    private _encService: EncService,
    private _dialg: MatDialog,
    private _functionsService: FunctionsService,
    private _socketService: SocketService,
    private _resourcesService: ResourcesService,
  ) { 
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.profiles = [];
    this.searching = false;
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';
    this.profilesHistoryEnabled = false;
    this.regEditProfileEnabled = false;
    this.viewPermissionsEnabled = false;
  }

  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 == 'S002V01M02USPE');
            if(modPerm.length > 0){
              let subPerm = modPerm[0].children.filter(item => item.id == 'S002V01S02GEPE');
              if(subPerm.length > 0){
                let funPerm = subPerm[0].children.filter(item => item.id == 'S002V01F01ADPE');
                if(funPerm.length > 0){
                  let profilesHistoryEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COPE');
                  if(profilesHistoryEnabled.length > 0){
                    this.profilesHistoryEnabled = profilesHistoryEnabled[0].access > 0;
                  }
                  
                  let regEditProfileEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02REPE');
                  if(regEditProfileEnabled.length > 0){
                    this.regEditProfileEnabled = regEditProfileEnabled[0].access > 0;
                  }

                  let viewPermissionsEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P03VEPE');
                  if(viewPermissionsEnabled.length > 0){
                    this.viewPermissionsEnabled = viewPermissionsEnabled[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 getData(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";

      let idEnc = localStorage.getItem('idusuario')!;
      let data: ProfilesResponse = await lastValueFrom(this._usersProfilesService.getProfiles(idEnc, 1));
      
      this.hasError = data.error;
      this.errorStr = data.msg;

      if(!this.hasError){
        let profiles: TableInfo[] = [];
        for(const profile of data.response){
          let lastDate = profile.FECMOD == null || profile.FECMOD == undefined ? profile.FECREG : profile.FECREG;
          let formattedDate = this._functionsService.orderDate(lastDate);

          let profileObj: TableInfo = {
            ID: await this._encService.decrypt(profile.IDPERFIL),
            NOMBRE: profile.NOMBREPERFIL,
            FECHA: formattedDate,
            ESTADO: profile.ESTADO
          }

          profiles.push(profileObj);
        }

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

        let permissionsEnc = localStorage.getItem('permisos');
        let permissionsDec = '';
        if(permissionsEnc == '' || permissionsEnc == null ||  permissionsEnc == undefined){
          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 == 'S002V01M02USPE');
          if(modPerm.length > 0){
            let subPerm = modPerm[0].children.filter(item => item.id == 'S002V01S02GEPE');
            if(subPerm.length > 0){
              let funPerm = subPerm[0].children.filter(item => item.id == 'S002V01F01ADPE');
              if(funPerm.length > 0){
                let profilesHistoryEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COPE');
                if(profilesHistoryEnabled.length > 0){
                  this.profilesHistoryEnabled = profilesHistoryEnabled[0].access > 0;
                }

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

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

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        console.log(error);
        this.errorStr = 'Ocurrió un error inesperado (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }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();
    }
  }

  openPermissions(profile: number, profileName: string, action: string){
    let dataobj = {
      profile: profile,
      profileName: profileName,
      action: action
    };

    let dataStr = JSON.stringify(dataobj);
    
    this._encService.encrypt(dataStr).then((dataEnc) =>{
      this._router.navigate([`sam/USPE/GEPE/ADPE/${action}`], action != 'crear' ? {
        queryParams: {
          info: dataEnc
        }
      } : undefined);
    });
  }

  openDialog(name: string, id: number){
    let dialog = this._dialg.open(AlertComponent, {
      width: '300px',
      data: {
        icon: "warning",
        title: '¡Cuidado!',
        description: `¿Está seguro de querer eliminar el perfil '${name}'?`,
        description2: "Esta acción no se puede deshacer."
      }
    });

    dialog.afterClosed().subscribe(res => {
      if(res == true){
        this.isLoading = true;
        this.hasError = false;
        this.errorStr = "";

        this.deleteProfile(id);
      }
    });
  }

  async deleteProfile(id: number){
    try{
      let perfEnc = await this._encService.encrypt(`${id}`);
      
      await lastValueFrom(this._usersProfilesService.deleteProfile({
        id: perfEnc,
        id_user: localStorage.getItem('idusuario'),
        linea: 1
      }));

      this._resourcesService.openSnackBar('El perfil se eliminó correctamente');
    }catch(error: any){
      let msg = "";

      if(error.error == undefined){
        msg = "Ocurrió un error inesperado.";
      }else if(error.error.msg == undefined){
        msg = "Ocurrió un error inesperado.";
      }else{
        msg = error.error.msg;
      }

      this._resourcesService.openSnackBar(msg);
    }
    this.getData();
  }
}
