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


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

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

  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]))
    }),tap(authorized => {
      if(!authorized){
        this.router.navigate(['/user-info'], {queryParams: {'errorCode': errorCode, 'redirectUrl':path}});
      }
    }));
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.check(state.url, route.params.stakeholder);
  }
  
  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.check(state.url, childRoute.data?.stakeholder?childRoute.data.stakeholder:childRoute.params.stakeholder);
  }
}
