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

import * as selectors from '../selectors';
import { getBudgetingTabAction, setBudgetingTabAction } from '../slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(getBudgetingTabAction.type),
    switchMap(() => {
      const setBudgeting = {};
      const state = state$.value;

      const info = selectors.infoSelector(state);

      if (info && info.budgets) {
        setBudgeting.budgetingTabList = info.budgets.map((item, index) => ({
          id: index,
          budget: item.budget,
          type: item.type,
          timeFrame: item.timeframe,
          pacing: item.pacing,
        }));
      }

      return concat(of(setBudgetingTabAction(setBudgeting)));
    }),
  );
