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 { TranslateService } from '@ngx-translate/core';

import { IInputDataUpload } from '../input-data-upload.model';
import { InputDataUploadService } from '../service/input-data-upload.service';

const inputDataUploadResolve = (route: ActivatedRouteSnapshot): Observable<null | IInputDataUpload> => {
  const router = inject(Router);
  const translate = inject(TranslateService);
  const inputDataUploadService = inject(InputDataUploadService);
  const id = route.params['id'];
  if (id) {
    return inject(InputDataUploadService)
      .find(id)
      .pipe(
        mergeMap((inputDataUploadResponse: HttpResponse<IInputDataUpload>) => {
          if (inputDataUploadResponse.body) {
            const inputDataUpload = inputDataUploadResponse.body;
            
            // Check if is /edit route, and the state of the InputDataUpload
            const path = route.routeConfig?.path;
            if (path && path.endsWith('/edit') && !inputDataUploadService.canUpdate(inputDataUpload)) {
              router.navigate(['/input-data-upload', id, 'view'], {
                state: { message: translate.instant('resilientApp.inputDataUpload.home.editNotAllowedForState') }
              });
              return EMPTY;
            } else {
              return of(inputDataUpload);
            }
          } else {
            router.navigate(['404']);
            return EMPTY;
          }
        }),
      );
  }
  return of(null);
};

export default inputDataUploadResolve;
