import { Injectable } from '@angular/core';
import { Route, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { first, map } from 'rxjs/operators';
import { MsgBoxService } from './msg-box.service';
import { NbAuthService } from '@nebular/auth';
import { NbDialogService } from '@nebular/theme';
import { AuthService } from './auth.service';
import { Role } from '../entity/Auth';
import { EnumUtils } from '../utilities/enum-utils';

@Injectable({
  providedIn: "root",
})
export class AuthGuardService  {

  constructor(
    private authService: AuthService,
    private router: Router,
    private http: HttpClient,
    private msgBoxService: MsgBoxService,
    private dialogService: NbDialogService,
  ) { }

  canLoad(route: Route): Observable<boolean> | boolean {

    const allowedRoles = route.data.roles as Role;
    return this.authService.isAuthenticated().pipe(map(result => {

      if (!result) {
        this.router.navigate([`/auth/login`],
          { queryParams: { return: this.router.url } });
        return true;
      }
      return true;
    }));
  }

  //canActivate is used for authentication
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | boolean {
    // if (this.authService.isLoggedIn()) {
    //   return true;
    // } else {
    //   this.router.navigate(["/auth/login"]);
    //   return false;
    // }

    const allowedRoles = route.data.roles as Role;
    return this.authService.isAuthenticated().pipe(map(result => {

      if (!result) {
        this.router.navigate([`/auth/login`],
          { queryParams: { return: state.url } });
        return false;
      }
      return true;
    }));

  }

  //canActivateChild is used for authorization
  //
  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | boolean {

    const allowedRoles = route.data.roles as Role;
    //const currentUser = this.authService.getToken();

    return this.authService.isAuthenticated().pipe(map(result => {

      if (!result) {
        this.router.navigate([`/auth/login`],
          { queryParams: { return: state.url } });
        return false;
      } else {

        if (route.data.roles && route.data.roles != Role.All &&

          false == EnumUtils.hasFlag(route.data.roles, result.role)) {
          this.router.navigate([`/home`]);
        }
      }
      return true;
    }));
  }


  // private TriggerInjectionUrl(key: string) {

  //   this.http.get<any>(this.injectionUrl[key]).pipe(first()).subscribe(result => {

  //   });
  //   return
  // }

  // private TriggerPopupUrl(key: string) {
  //   this.dialogService.open(this.popupUrls[key].type, this.popupUrls[key].args)
  // }

}