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

@Injectable()
export class ConnectSubscriberGuard implements CanActivate, CanActivateChild {
  
  constructor(private router: Router,
              private userManagementService: UserManagementService) {
  }
  
  check(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    let errorCode = LoginErrorCodes.NOT_SUBSCRIBER;
    let community;
    if(properties.isDashboard) {
      community = route.params['community'];
    } else {
      community = ConnectHelper.getCommunityFromDomain(properties.domain);
    }
    const authorized = this.userManagementService.getUserInfo().pipe(take(1), map(user => {
      if (user) {
        if (Session.isSubscribedTo('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': state.url
        }
      })
    });
    return authorized;
  }
  
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.check(route, state);
  }
  
  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.check(childRoute, state);
  }
}
