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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { exportToPDFAction, setFieldAction } from '../slices';
import { html2pdf } from '@/modules/analytics/common/helpers';
import { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$) =>
  action$.pipe(
    ofType(exportToPDFAction.type),
    switchMap((action) => {
      const stream$ = defer(async () => html2pdf('live-dashboard', action.payload)).pipe(
        switchMap(() =>
          concat(
            of(
              showNotificationAction({
                type: TYPE_SUCCESS,
                message: 'Download was successful',
              }),
            ),
          ),
        ),
      );

      return concat(
        of(setFieldAction({ isExportPdfLoading: true })),
        stream$,
        of(setFieldAction({ isExportPdfLoading: false })),
      );
    }),
  );
