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

import { configCopySelector } from '../selectors';
import {
  configAction,
  configChangedEventAction,
  configCopyAction,
  isFilterDirtyAction,
  restoreConfigAction,
} from '../slices';
import { deepClone } from '@/modules/@common/helpers';

export default (action$, state$) =>
  action$.pipe(
    ofType(restoreConfigAction.type),
    filter((action) => configCopySelector(state$.value) || action.payload),
    switchMap((action) => {
      const actions = [];
      actions.push(
        of(configAction(deepClone(action.payload ? action.payload : configCopySelector(state$.value)))),
        of(configChangedEventAction()),
        of(configCopyAction(null)),
        of(isFilterDirtyAction(true)),
      );

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