import Router from 'next/router';
import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

import { EDITORIAL_PAGE } from '@/modules/@common/router/constants';

import { monitoringSelector } from '../selectors';
import { loadAction, monitoringInProgressAction, monitoringStartAction } from '../slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(monitoringInProgressAction.type),
    filter((action) => action.payload === false && monitoringSelector(state$.value) === true),
    switchMap(() => {
      const isEditorialPage = Router.pathname === EDITORIAL_PAGE.path;
      const actions = [];

      if (!isEditorialPage) {
        actions.push(of(loadAction()));
      }

      actions.push(of(monitoringStartAction()));

      return concat(...actions);
    }),
  );
