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('video-content-performance', 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 })),
      );
    }),
  );
