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

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

let IS_INITIAL = true;

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

      if (!video?.uid || !job || (IS_INITIAL && job?.state === JOB_STATE_DONE)) {
        return EMPTY;
      }

      const actions = [];
      IS_INITIAL = false;

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

      if ((job.state === JOB_STATE_DONE || job.state === JOB_STATE_ERROR) && processing) {
        IS_INITIAL = true;
        actions.push(
          of(
            setAction({
              processing: false,
              isEditMode: false,
              processingPercentage: null,
              currentProcessingJobType: null,
            }),
          ),
          of(getTranslationFilesAction()),
        );
      }

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