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 { IVariable } from '../variable.model';
import { VariableService } from '../service/variable.service';

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

export default variableResolve;
