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

import {
  JOB_STATE_DONE,
  JOB_STATE_ERROR,
  JOB_STATE_PROCESSING,
  JOB_STATE_START,
  JOB_TYPE_VIDEO_HIGHLIGHTS_PROCESSING,
} from '../../constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { selectedVideoSelector } from '../../../AiWorkbench/redux/selectors';
import { processingSelector } from '../selectors';
import { getHighlightsAction, setAction } from '../slices';
import { monitoringDataAction } from '@/modules/editorial/editorialSearch/redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(monitoringDataAction.type),
    switchMap((action) => {
      const job = action.payload.find((o) => o.type === JOB_TYPE_VIDEO_HIGHLIGHTS_PROCESSING);
      const processing = processingSelector(state$.value);
      const video = selectedVideoSelector(state$.value);

      if (!job || !video?.uid) {
        return EMPTY;
      }

      const actions = [];

      if (job.state === JOB_STATE_START || job.state === JOB_STATE_PROCESSING) {
        actions.push(
          of(
            setAction({
              processing: true,
              processingPercentage: job.progress === 100 ? 99 : job.progress,
              currentProcessingJobType: JOB_TYPE_VIDEO_HIGHLIGHTS_PROCESSING,
            }),
          ),
        );
      }

      if (job.state === JOB_STATE_DONE && processing) {
        actions.push(
          of(setAction({ processing: false, processingPercentage: null, currentProcessingJobType: null })),
          of(
            getHighlightsAction({
              shouldShowGenerationsCompletedNotification: true,
            }),
          ),
        );
      }

      if (job.state === JOB_STATE_ERROR && processing) {
        actions.push(
          of(setAction({ processing: false, processingPercentage: null, currentProcessingJobType: null })),
          of(
            showNotificationAction({
              type: TYPE_ERROR,
              message: 'Highlights cannot be created for this video.',
            }),
          ),
        );
      }

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