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 { IUnitConverter } from '../unit-converter.model';
import { UnitConverterService } from '../service/unit-converter.service';

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

export default unitConverterResolve;
