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

@Injectable()
export class ConnectAdminLoginGuard  {
  
  constructor(private router: Router,
              private userManagementService: UserManagementService) {
  }
  
  check(community: string, path: string): Observable<boolean> | boolean {
    let errorCode = LoginErrorCodes.NOT_LOGIN;
    const authorized = this.userManagementService.getUserInfo().pipe(take(1), map(user => {
      if (user) {
        errorCode = LoginErrorCodes.NOT_ADMIN;
        if (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user) || Session.isManager('community', community, user)) {
          return of(true);
        }
      }
      return of(false);
    }), mergeMap(authorized => {
      return authorized;
    }));
    authorized.pipe(filter(authorized => !authorized)).subscribe(() => {
      this.router.navigate(['/user-info'], {
        queryParams: {
          'errorCode': errorCode,
          'redirectUrl': path
        }
      })
    });
    return authorized;
  }
  
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.check(route.params['community'], state.url);
  }
  
  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.check(childRoute.params['community'], state.url);
  }
}
