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

import {map, take, tap} 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 {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";
import {zip} from "rxjs";


@Injectable()
export class AdminDashboardGuard implements CanActivate {

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

  check(path: string, alias: string): Observable<boolean> | boolean {
    if (Session.isLoggedIn()) {
      return zip(
        this.userManagementService.getUserInfo(false)
        ,this.stakeholderService.getStakeholder(alias)
      ).pipe(take(1),map(res =>{
        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': LoginErrorCodes.NOT_ADMIN, 'redirectUrl':path}});
        }
      }));

    } 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, route.params.stakeholder);
  }
}
