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

import { hasNoValue, hasValue } from '../../shared/empty.util';
import { CommunityDataService } from '../../core/data/community-data.service';
import { RemoteData } from '../../core/data/remote-data';
import { Community } from '../../core/shared/community.model';
import { getFinishedRemoteData } from '../../core/shared/operators';
import { map, tap } from 'rxjs/operators';
import { Observable, of as observableOf } from 'rxjs';

/**
 * Prevent creation of a community with an invalid parent community provided
 * @class CreateCommunityPageGuard
 */
@Injectable()
export class CreateCommunityPageGuard implements CanActivate {
  public constructor(private router: Router, private communityService: CommunityDataService) {
  }

  /**
   * True when either NO parent ID query parameter has been provided, or the parent ID resolves to a valid parent community
   * Reroutes to a 404 page when the page cannot be activated
   * @method canActivate
   */
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    const parentID = route.queryParams.parent;
    if (hasNoValue(parentID)) {
      return observableOf(true);
    }

    const parent: Observable<RemoteData<Community>> = this.communityService.findById(parentID)
      .pipe(
        getFinishedRemoteData(),
      );

    return parent.pipe(
      map((communityRD: RemoteData<Community>) => hasValue(communityRD) && communityRD.hasSucceeded && hasValue(communityRD.payload)),
      tap((isValid: boolean) => {
        if (!isValid) {
          this.router.navigate(['/404']);
        }
      })
    );
  }
}
