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

import { of, Observable, BehaviorSubject } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { UsersService } from './users.service';


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

  private userInfo: BehaviorSubject<any> = new BehaviorSubject(null);

  // Inject Router so we can hand off the user to the Login Page 
  constructor(private _userService: UsersService, private httpClient: HttpClient, private router: Router) {
    var user = localStorage.getItem("user");
    this.userInfo.next(JSON.parse(user));
  }

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    console.log("CanActivate?");
    return this._userService.getMe().pipe(
      map(res => {
        localStorage.setItem("user", JSON.stringify(res));
        this.userInfo.next(res);
        return true;
      }),
      catchError((err) => {
        this.clearUser();
        return of(false);
      })
    );
  }

  

  clearUser() {
    localStorage.setItem("user", null);
    this.userInfo.next(null);
  }

  getUserInfo(): any {
    return this.userInfo;
  }
}


