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 { IMetadataValue } from '../metadata-value.model';
import { MetadataValueService } from '../service/metadata-value.service';

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

export default metadataValueResolve;
