import {AdminDashboardGuard} from "../openaireLibrary/monitor-admin/utils/adminDashboard.guard";
import {Injectable} from "@angular/core";
import {ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree} from "@angular/router";
import {Observable} from "rxjs";
import {properties} from "../../environments/environment";
import {LoginErrorCodes} from "../openaireLibrary/login/utils/guardHelper.class";
import {map, tap} from "rxjs/operators";
import {Session} from "../openaireLibrary/login/utils/helper.class";

@Injectable({
  providedIn: 'root'
})
export class SandboxGuard extends AdminDashboardGuard {

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    let sandbox = properties.environment === 'beta';
    if(childRoute.data['researcher'] && childRoute.params.stakeholder && sandbox) {
      let errorCode = LoginErrorCodes.NOT_LOGIN;
      let alias = childRoute.params.stakeholder;
      return this.userManagementService.getUserInfo().pipe(map(user => {
        if(user) {
          errorCode = LoginErrorCodes.NOT_ADMIN;
        }
        return user && (Session.isPortalAdministrator(user) ||
            Session.isCurator('researcher', user) || user?.orcid === alias);
      }), tap(authorized => {
        if(!authorized){
          this.router.navigate(['/user-info'], {queryParams: {'errorCode': errorCode, 'redirectUrl':state.url}});
        }
      }));
    } else {
      return !sandbox || super.canActivateChild(childRoute, state);
    }
  }
}
