import { CanActivateFn, Router } from '@angular/router';
import { LoginDataService } from '../services/login-data.service';
import { inject } from '@angular/core';
import { SocketService } from '../services/socket.service';
import { MatSnackBar } from '@angular/material/snack-bar';

export const authGuard: CanActivateFn = async (route, state) => {
  const loginDataService: LoginDataService = inject(LoginDataService);
  const router: Router = inject(Router);
  const socketService: SocketService = inject(SocketService);
  const snackBar: MatSnackBar = inject(MatSnackBar);

  let hasInfo = loginDataService.isLogin();
  if(!hasInfo){
    loginDataService.logout();
    router.navigate(['login']);

    return false;
  }else{
    let token = localStorage.getItem('token')!;
    let idusuario = localStorage.getItem('idusuario')!;
    let verify = await loginDataService.verifyToken(token);

    if(verify){
      socketService.register();

      let socketInfoObj = {
        token: token,
        user: idusuario
      };

      let socketInfoStr = JSON.stringify(socketInfoObj);
      socketService.deleteSession(socketInfoStr)
      socketService.saveSession(socketInfoStr);
      
      return true;
    }else{
      snackBar.open('Token expirado.', undefined, {
        duration: 5000,
      });

      loginDataService.logout();
      router.navigate(['login']);
      
      return false;
    }
  }
};
