import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AccountService } from '../server-services/account.service';
import { AuthService } from '../server-services/auth.service';
import { RouterHandler } from '../services/router-handler.service';

@Injectable({
  providedIn: 'root'
})
export class IsLoggedInGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router, private routerHandler: RouterHandler){}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    if(route.url.some(url => url.path == "login" || url.path == "register")){ //on login or register page, we have to do the opposite
      if(this.authService.isAnonym())
        return true;
      else
        return this.router.parseUrl("");
    }
    else //navigate to login if no user is logged in
    {
      if(this.authService.isAnonym())
        return this.router.parseUrl("/login");
      else
        return true;
    }
  }
}
