import { Permissions } from 'src/app/interfaces/permissions.interface';
import { EncService } from './../../../services/enc/enc.service';
import { MatPaginator } from '@angular/material/paginator';
import { DeleteAlertComponent } from './delete-alert/delete-alert.component';
import { NewPasswordComponent } from './new-password/new-password.component';
import { MatSnackBar } from '@angular/material/snack-bar';
import { UsersResponse, UserResponse } from './../../../interfaces/users.interface';
import { UsersProfilesService } from './../../../services/users-profiles.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { Location } from '@angular/common';
import { SocketService } from 'src/app/services/socket.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';

@Component({
  selector: 'app-users-admin',
  templateUrl: './users-admin.component.html',
  styleUrls: ['./users-admin.component.css']
})
export class UsersAdminComponent implements OnInit {
  public btnSmall: boolean = false;
  public txtBuscador:string;

  users: Array<UserResponse>;
  errorStr: string;
  modIcon: string;
  modName: string;
  menuIcon: string;
  menuName: string;

  isLoading: boolean;
  hasError: boolean;
  usersFinded: Array<UserResponse>;

  displayedColumns: string[] =  ['ID', 'NOMBRE', 'APEPAT', 'APEMAT', 'PERFIL', 'ESTATUS', 'EMAIL', 'ACCIONES'];
  dataSource?: MatTableDataSource<UserResponse>;

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

  usersConsultEnabled: boolean;
  regEditUserEnabled: boolean;
  blockUnblockEnabled: boolean;
  changePasswordEnabled: boolean;

  constructor(
    private _usersProfilesService: UsersProfilesService, 
    private _snackBar: MatSnackBar, 
    private _router: Router,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _socketService: SocketService,
  ) { 
    this.users = [];
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.modIcon = "";
    this.modName = "";
    this.menuIcon = "";
    this.menuName = "";
    this.txtBuscador = '';

    this.usersFinded = [];
    this.btnSmall = window.innerWidth <= 1405;
    this.usersConsultEnabled = true;
    this.regEditUserEnabled = true;
    this.blockUnblockEnabled = true;
    this.changePasswordEnabled = true;
  }

  ngOnInit(): void {
    this.getData();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      let shortID = await lastValueFrom(this._encService.shortEncrypt(localStorage.getItem('idusuario')!));
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(shortID.response.encrypted, shortID.response.encrypted, 1));
      let currentProfile = await this._encService.desencriptar(localStorage.getItem('perfil')!);

      if(parseInt(currentProfile) != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.desencriptar(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        try{
          let shortProf = await lastValueFrom(this._encService.shortEncrypt(localStorage.getItem('perfil')!));
          let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
            shortProf.response.encrypted,
            shortID.response.encrypted,
            1
          ));

          let modPerm = profInfo.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M02USPE')[0];
          let subPerm = modPerm.children.filter(item => item.id == 'S002V01S01GEUS')[0];
          let funPerm = subPerm.children.filter(item => item.id == 'S002V01F01ADUS')[0];
  
          this.usersConsultEnabled = funPerm.children.filter(item => item.id == 'S002V01P01COUS')[0].access > 0;
          this.regEditUserEnabled = funPerm.children.filter(item => item.id == 'S002V01P02RAUS')[0].access > 0;
  
          this.blockUnblockEnabled = subPerm.children.filter(item => item.id == 'S002V01F02BDAC')[0].access > 0;
          this.changePasswordEnabled = subPerm.children.filter(item => item.id == 'S002V01F03RECO')[0].access > 0;
        }catch(error: any){
          if(error.error == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else if(error.error.msg == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else{
            this.openSnackBar(error.error.msg);
          }
        }
      }
    });
  }

  async getData(){
    this.users = [];
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    
    try{
      let idEnc = localStorage.getItem('idusuario');
      let idShort = await lastValueFrom(this._encService.shortEncrypt(idEnc!));
      
      let data: UsersResponse = await lastValueFrom(this._usersProfilesService.getUsers(idShort.response.encrypted, 1));
      let idDec = await this._encService.desencriptar(idEnc!);

      this.hasError = data.error;
      this.errorStr = data.msg;
    
      if(!this.hasError){
        data.response.forEach((item: UserResponse) => {
          let usr: UserResponse = {
            IDUSUARIO: item.IDUSUARIO,
            NOMBRE: item.NOMBRE,
            APEPAT: item.APEPAT,
            APEMAT: item.APEMAT == null ? '-' : item.APEMAT,
            EMAIL: item.EMAIL,
            PERFIL: item.PERFIL,
            ESTATUS: item.ESTATUS
          };

          if(idDec != usr.IDUSUARIO) this.users.push(usr);
        });

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

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

        let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M02USPE')[0];
        let subPerm = modPerm.children.filter(item => item.id == 'S002V01S01GEUS')[0];
        let funPerm = subPerm.children.filter(item => item.id == 'S002V01F01ADUS')[0];

        this.usersConsultEnabled = funPerm.children.filter(item => item.id == 'S002V01P01COUS')[0].access > 0;
        this.regEditUserEnabled = funPerm.children.filter(item => item.id == 'S002V01P02RAUS')[0].access > 0;
  
        this.blockUnblockEnabled = subPerm.children.filter(item => item.id == 'S002V01F02BDAC')[0].access > 0;
        this.changePasswordEnabled = subPerm.children.filter(item => item.id == 'S002V01F03RECO')[0].access > 0;
      }

      this.isLoading = false;
    }catch(error:any){
      this.isLoading = false;
      this.hasError = true;
      this.errorStr = error.error.msg;
    }
  }

  openDialog(usr: string){
    const dialogRef = this._dialog.open(NewPasswordComponent, {
      data: {
        id: usr
      }
    });

    dialogRef.afterClosed().subscribe(result => {
      if(result != "" && result != undefined){
        this.updatePass(result.id, result.password, result.password_confirmation);
      }
    });
  }

  async updatePass(id: string, pass: string, passConf: string){
    try{
      let idEnc = await this._encService.encriptar(id);
      let idUser = localStorage.getItem('idusuario');
      console.log(idUser);
      
      /*
      await lastValueFrom(this.usersProfilesService.updatePwd({
        id: idEnc,
        id_user: idUser,
        password: pass,
        password_confirmation: passConf,
        linea: 1
      }));

      this.openSnackBar('La contraseña fue actualizada correctamente.');
      this.isLoading = true;
      this.getData();*/
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  openAlert(usr: string){
    const dialogRef = this._dialog.open(DeleteAlertComponent, {
      data: {
        id: usr
      }
    });

    dialogRef.afterClosed().subscribe(async result => {
      if(result != undefined){
        if(result){
          try{
            let idEnc = await this._encService.encriptar(usr);
            let idUser = localStorage.getItem('idusuario');
            
            await lastValueFrom(this._usersProfilesService.deleteUser({
              id: idEnc,
              id_user: idUser,
              linea: 1
            }));
            
            this.openSnackBar('El usuario se eliminó correctamente');
            this.isLoading = true;
            this.getData();
          }catch(error: any){
            this.openSnackBar(error.error.msg);
          }
        }
      }
    });
  }

  openSnackBar(message: string){
    this._snackBar.open(message, "Cerrar", {
      duration: 1500
    });
  }

  async blockUser(id: string){
    let idUser = localStorage.getItem('idusuario');
    let user = this.users.filter(item => item.IDUSUARIO == id)[0];
    let idEnc = await this._encService.encriptar(user.IDUSUARIO);
    let lastStatus = user.ESTATUS;
    let newStatus = lastStatus == 'Activo' ? 'Inactivo' : 'Activo';

    try{
      await lastValueFrom(this._usersProfilesService.blockUser({
        id: idUser,
        estatus: newStatus,
        id_user: idEnc,
        linea: 1
      }));

      this.isLoading = true;
      this.getData();
      this.openSnackBar('El usuario fue actualizado correctamente.');
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  async openUser(action: string, user: string){
    let params = {
      action: action,
      user: user
    };

    let paramsStr = JSON.stringify(params);
    let paramsEnc = await this._encService.encriptar(paramsStr);
    
    this._router.navigate(['sam/USPE/GEUS/ADUS/crear'], {
      queryParams: {
        info: paramsEnc,
      }
    });
  }

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

  goBack(steps: number){
    window.history.go(steps * -1);
  }

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