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 { IPeriodVersion } from '../period-version.model';
import { PeriodVersionService } from '../service/period-version.service';

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

export default periodVersionResolve;
