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 { IPeriod } from '../period.model';
import { PeriodService } from '../service/period.service';

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

export default periodResolve;
