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

import { dataSelector } from '../selectors';
import { dataAction, runAction, startAction } from '../slices';

const monitoringEpic = (action$, state$) =>
  action$.pipe(
    ofType(startAction.type),
    filter(({ payload }) => {
      const monitoringData = dataSelector(state$.value);

      return !monitoringData[payload];
    }),
    switchMap(({ payload }) => {
      const monitoringData = dataSelector(state$.value);

      return concat(of(dataAction({ ...monitoringData, ...{ [payload]: [] } })), of(runAction(payload)));
    }),
  );

export default monitoringEpic;
