import { Observable } from 'rxjs';

import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree,
  Router
} from '@angular/router';

import { AppAuthenticationService } from '@app/services/app-authentication.service';

@Injectable({
  providedIn: 'root'
})
export class AppAuthenticationGuard implements CanActivate {
  constructor(
    private appAuthenticationService: AppAuthenticationService,
    private router: Router
  ) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    | boolean
    | UrlTree
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree> {
    return new Promise<boolean | UrlTree>((resolve, reject) => {
      if (this.appAuthenticationService.loggedIn()) {
        resolve(true);
      } else {
        this.router.navigateByUrl('/account/login');
        resolve(false);
      }
    });
  }
}
