import { inject } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { of, EMPTY, Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

import { IVariableScope } from '../variable-scope.model';
import { VariableScopeService } from '../service/variable-scope.service';

const variableScopeResolve = (route: ActivatedRouteSnapshot): Observable<null | IVariableScope> => {
  const id = route.params['id'];
  if (id) {
    return inject(VariableScopeService)
      .find(id)
      .pipe(
        mergeMap((variableScope: HttpResponse<IVariableScope>) => {
          if (variableScope.body) {
            return of(variableScope.body);
          } else {
            inject(Router).navigate(['404']);
            return EMPTY;
          }
        }),
      );
  }
  return of(null);
};

export default variableScopeResolve;
