import { Injectable } from '@angular/core';
import { ActivatedRoute, ActivatedRouteSnapshot, Route, Router, RouterStateSnapshot, UrlSegment, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from 'src/app/modules/auth.service';


@Injectable({
  providedIn: 'root'
})
export class AuthGuard  {
  constructor(private router: Router, private activatedRoute: ActivatedRoute, private authService: AuthService) {}

  private async check(): Promise<boolean> {
    console.log("checking")
    if (this.authService.isLoggedIn()) { return true; }
    const success = await this.authService.loginFromLocalStorage();
    if (success) {
      return true;
    }

    this.router.navigate(['/auth']).then();
    return false;
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.check();
  }
  canActivateChild(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      return this.check();
  }
  canLoad(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      return this.check();
  }
}