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 { IMetadataProperty } from '../metadata-property.model';
import { MetadataPropertyService } from '../service/metadata-property.service';

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

export default metadataPropertyResolve;
