import { Injectable } from '@angular/core';
import { Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard  {
  loginUrl: string | null = null;
  constructor(
    private auth$: AuthService,
    private router$: Router,
  ) {}
  canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.auth$.isAuthenticated()) {
      if (this.loginUrl) {
        this.router$.navigate([this.loginUrl]);
        this.loginUrl = null;
      }
      return true;
    } else {
      return this.tryWaitForAuthData();
    }
  }  
  async tryWaitForAuthData(): Promise<boolean> {
    return new Promise((resolve) => {
      setTimeout(() => {
        if (this.auth$.isAuthenticated()) {
          resolve(true);
        } else {
          this.loginUrl = window.location.pathname;
          this.router$.navigate(['']);
          resolve(false);
        }
      }, 100);
    })
  }
}
