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

import * as selectors from '../selectors';
import { saveToCSVAction } from '../slices';
import { downloadTableToCSV } from '@/modules/marketplace/common/helpers';

export default (action$, state$) =>
  action$.pipe(
    ofType(saveToCSVAction.type),
    filter(() => {
      const state = state$.value;

      const pageConfig = selectors.pageConfigSelector(state);

      return !!pageConfig;
    }),
    switchMap(({ payload }) => {
      const state = state$.value;

      const pageConfig = selectors.pageConfigSelector(state);
      const activeTabIndex = selectors.activeTabIndexSelector(state);

      const tabs = payload?.isAdminMP ? pageConfig.tabs : pageConfig.selfServeTabs;

      downloadTableToCSV({
        headers: tabs[activeTabIndex].tableHeaders,
        cells: tabs[activeTabIndex].tableCells,
        data: payload?.data ?? [],
        fileName: tabs[activeTabIndex].label,
      });

      return concat();
    }),
  );
