import { ActivatedRouteSnapshot, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import {SecurityService} from './app/logic/services/security.service';

@Injectable()
export class AuthGuard implements CanActivateChild {

  constructor(private router: Router,
              private securityService: SecurityService) {
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    const loggedIn = this.securityService.loggedIn();

    if (childRoute.routeConfig.path === 'login') {
      return !loggedIn;
    }

    if (!loggedIn) {
      this.router.navigate(['login']);
    }

    return loggedIn;
  }
}
