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

import {filter, map} from "rxjs/operators";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
import {LoginErrorCodes} from "../openaireLibrary/login/utils/guardHelper.class";
import {Session} from "../openaireLibrary/login/utils/helper.class";
import {properties} from "../../environments/environment";

@Injectable()
export class AdminDashboardGuard implements CanActivate, CanLoad {

  constructor(private router: Router,
              private userManagementService: UserManagementService) {
  }

  check(path: string): Observable<boolean> | boolean {
 /* //Argiro testing
    if(properties.environment == "development"){
      return true;
    }*/
    if (Session.isLoggedIn()) {
      const obs = this.userManagementService.getUserInfo(false).pipe(map(user => {
        return  (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user) || Session.isMonitorCurator(user));
      }));
      obs.pipe(filter(isLoggedIn => !isLoggedIn)).subscribe(() => {
        this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_ADMIN, 'redirectUrl':path}});
      });
      return obs;
    } else {
      this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_LOGIN, 'redirectUrl':path}});
      return false;
    }
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    return this.check(state.url);
  }

  canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
    return this.check('/' + route.path);
  }
}
