import { FunctionsService } from './../../../services/functions.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { AlertComponent } from './../../resources/dialogs/alert/alert.component';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from './../../../services/enc/enc.service';
import { lastValueFrom } from 'rxjs';
import { Router } from '@angular/router';
import { ProfilesResponse, ProfileResponse } from './../../../interfaces/profiles.interface';
import { UsersProfilesService } from './../../../services/users-profiles.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { Permissions } from 'src/app/interfaces/permissions.interface';
import { SocketService } from 'src/app/services/socket.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';

interface TableInfo{
  ID: number,
  NOMBRE: string,
  FECHA: string,
  ESTADO: string 
}

@Component({
  selector: 'app-profiles-admin',
  templateUrl: './profiles-admin.component.html',
  styleUrls: ['./profiles-admin.component.css']
})
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 _snackBar: MatSnackBar,
    private _functionsService: FunctionsService,
    private _socketService: SocketService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.profiles = [];
    this.searching = false;
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';
    this.profilesHistoryEnabled = true;
    this.regEditProfileEnabled = true;
    this.viewPermissionsEnabled = 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 == 'S002V01S02GEPE')[0];
          let funPerm = subPerm.children.filter(item => item.id == 'S002V01F01ADPE')[0];

          this.profilesHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P01COPE')[0].access > 0;
          this.regEditProfileEnabled = funPerm.children.filter(item => item.id == 'S002V01P02REPE')[0].access > 0;
          this.viewPermissionsEnabled = funPerm.children.filter(item => item.id == 'S002V01P03VEPE')[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.profiles = [];
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    
    try{
      let idEnc = localStorage.getItem('idusuario');
      let idShort = await lastValueFrom(this._encService.shortEncrypt(idEnc!));
      
      let data: ProfilesResponse = await lastValueFrom(this._usersProfilesService.getProfiles(idShort.response.encrypted, 1));
      
      this.hasError = data.error;
      this.errorStr = data.msg;

      if(!this.hasError){
        data.response.forEach((item: ProfileResponse) => {
          let lastDate = item.FECHAMODIFICACION == null || item.FECHAMODIFICACION == undefined ? item.FECHACREACION : item.FECHAMODIFICACION;
          let formattedDate = this._functionsService.orderDate(lastDate);
          
          let profile: TableInfo = {
            ID: item.IDPERFIL,
            NOMBRE: item.NOMBREPERFIL,
            FECHA: formattedDate,
            ESTADO: item.ESTATUS
          };
          
          this.profiles.push(profile)
        });

        this.dataSource = new MatTableDataSource(this.profiles);
        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 == 'S002V01S02GEPE')[0];
        let funPerm = subPerm.children.filter(item => item.id == 'S002V01F01ADPE')[0];

        this.profilesHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P01COPE')[0].access > 0;
        this.regEditProfileEnabled = funPerm.children.filter(item => item.id == 'S002V01P02REPE')[0].access > 0;
        this.viewPermissionsEnabled = funPerm.children.filter(item => item.id == 'S002V01P03VEPE')[0].access > 0;
      }

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

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

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

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

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

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

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

      this.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.openSnackBar(msg);
    }
    this.getData();
  }

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

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