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

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

const JOB_TYPE = 'DESCRIPTIONS';
const JOB_STATE_START = 'STARTED';
const JOB_STATE_DONE = 'DONE';
const JOB_STATE_PROCESSING = 'PROCESSING';

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 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,
            }),
          ),
        );
      }

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

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