import {AdminDashboardGuard} from "../openaireLibrary/monitor-admin/utils/adminDashboard.guard";
import {Injectable} from "@angular/core";
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree} from "@angular/router";
import {Observable, zip} from "rxjs";
import {properties} from "../../environments/environment";
import {LoginErrorCodes} from "../openaireLibrary/login/utils/guardHelper.class";
import {map, take, tap} from "rxjs/operators";
import {Session} from "../openaireLibrary/login/utils/helper.class";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
import {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";

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

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

  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) {
      return this.checkResearcher(state.url, childRoute.params.stakeholder);
    } else {
      let alias = childRoute.params.stakeholder;
      let route = childRoute;
      while (!alias && route) {
        alias = route.data.stakeholder;
        route = route.parent;
      }
      return !sandbox || this.check(state.url, alias);
    }
  }

  checkResearcher(path: string, alias: string) {
    let errorCode = LoginErrorCodes.NOT_LOGIN;
    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': path}});
      }
    }));
  }

  check(path: string, alias: string): Observable<boolean> | boolean {
    let errorCode = LoginErrorCodes.NOT_LOGIN;
    return zip(
        this.userManagementService.getUserInfo(), this.stakeholderService.getStakeholder(alias)
    ).pipe(take(1), map(res => {
      if (res[0]) {
        errorCode = LoginErrorCodes.NOT_ADMIN;
      }
      return res[0] && res[1] && (Session.isPortalAdministrator(res[0]) ||
          Session.isCurator(res[1].type, res[0]) ||
          Session.isManager(res[1].type, res[1].alias, res[0]) ||
          Session.isMember(res[1].type, res[1].alias, res[0]))
    }), tap(authorized => {
      if (!authorized) {
        this.router.navigate(['/user-info'], {queryParams: {'errorCode': errorCode, 'redirectUrl': path}});
      }
    }));
  }
}
