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


import { Store } from '@ngrx/store';
import { OAuthService } from 'angular-oauth2-oidc';


import * as appCommonReducer from '../reducers/app-common.reducer'
import * as appCommonActions from '../actions/app-common.actions';


@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanLoad, CanActivateChild  { 
 
  constructor(private oauthService: OAuthService, private router: Router, private store: Store<appCommonReducer.State> ) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  canLoad(route: Route): Promise<boolean> {
    return this.checkLogin(route.path);
  }

  checkLogin(url: string): Promise<boolean> {
    return new Promise<boolean>((resolve) => {
      if (!this.oauthService.hasValidAccessToken()) {
        console.debug("No valid token");
        this.oauthService.initCodeFlow(url);
        resolve(false);
      } else {        
        resolve(true);
      }
    });
  }
}
