import Router from 'next/router';
import { ofType } from 'redux-observable';
import { timer } from 'rxjs';
import { debounce, filter, mapTo } from 'rxjs/operators';

import { hasUnfinishedJobs } from '../../helpers/helpers/monitoring';
import { monitoringAction, monitoringDataAction } from '../slices';

export default (action$) =>
  action$.pipe(
    ofType(monitoringDataAction.type),
    debounce(() => {
      const delay = Router.query?.aiworkbench ? 2000 : +process.env.APP_REQUEST_TIMEOUT;
      return timer(delay);
    }),
    filter((action) => hasUnfinishedJobs(action.payload)),
    mapTo(monitoringAction(true)),
  );
