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 { IEmissionFactor } from '../emission-factor.model';
import { EmissionFactorService } from '../service/emission-factor.service';

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

export default emissionFactorResolve;
