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 { IInputData } from '../input-data.model';
import { InputDataService } from '../service/input-data.service';

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

export default inputDataResolve;
