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';

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 {
  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;

  constructor(
    private usersProfilesService: UsersProfilesService, 
    private router: Router, 
    private encService: EncService,
    private dialg: MatDialog,
    private _snackBar: MatSnackBar,
    private _functionsService: FunctionsService
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.profiles = [];
    this.searching = false;
  }

  ngOnInit(): void {
    this.getData();
  }

  async getData(){
    this.profiles = [];
    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));
      console.log(data);
      
      if(data.error){
        this.isLoading = false;
        this.hasError = true;
        this.errorStr = data.msg;
      }else{
        this.isLoading = false;
        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!;
      }
    }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: Event){
    const filterValue = (event.target as HTMLInputElement).value;
    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(msg: string){
    this._snackBar.open(msg, 'Cerrar', {
      duration: 5000
    })
  }

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