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_THUMBNAILS_CURRENT_FRAME_PROCESSING as JOB_TYPE,
} from '../../constants';

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

export default (action$, state$) =>
  action$.pipe(
    ofType(monitoringDataAction.type),
    switchMap((action) => {
      const job = action.payload.find((o) => o.type === JOB_TYPE);
      const processing = processingSelector(state$.value);
      const processingJob = processingJobSelector(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,
              processingJob: JOB_TYPE,
              processingPercentage: job.progress === 100 ? 99 : job.progress,
            }),
          ),
        );
      }

      if ([JOB_STATE_ERROR, JOB_STATE_DONE].includes(job.state) && processing && processingJob === JOB_TYPE) {
        actions.push(
          of(setAction({ processing: false, processingPercentage: null, processingJob: null })),
          of(
            getThumbnailAction({
              processingComplete: true,
              processingJob: JOB_TYPE,
            }),
          ),
        );
      }

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