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

import {
  UPLOAD_FLOW_CREATE_VIDEO_VERSION,
  UPLOAD_STATUS_UPLOADING,
  UPLOAD_STATUS_WAIT,
} from '@/modules/uploaderNew/constants';

import { queueSelector } from '../selectors';
import {
  chooseUploadBranchAction,
  chooseVideoVersionUploadBranchAction,
  setProcessUploadQueueIdAction,
  setProcessUploadStatusAction,
  startUploadFromQueueAction,
} from '../slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(startUploadFromQueueAction.type),
    switchMap((action) => {
      const queue = queueSelector(state$.value);
      const queueIds = Object.keys(queue);

      const waitForUpload = queueIds.filter((id) => {
        const qItem = queue[id];
        return qItem.processedUploadStatus === UPLOAD_STATUS_WAIT;
      });

      const activeProcessedUploadQueueId = waitForUpload[0];

      const hasUploadingInProgress = queueIds.some((id) => {
        const qItem = queue[id];
        return qItem.processedUploadStatus === UPLOAD_STATUS_UPLOADING;
      });

      if (!hasUploadingInProgress && activeProcessedUploadQueueId) {
        const actions = [
          of(setProcessUploadQueueIdAction(activeProcessedUploadQueueId)),
          of(
            setProcessUploadStatusAction({
              status: UPLOAD_STATUS_UPLOADING,
              processedUploadQueueId: activeProcessedUploadQueueId,
            }),
          ),
        ];

        if (action.payload !== UPLOAD_FLOW_CREATE_VIDEO_VERSION) {
          actions.push(of(chooseUploadBranchAction()));
        } else {
          actions.push(of(chooseVideoVersionUploadBranchAction()));
        }

        return concat(...actions);
      }

      return EMPTY;
    }),
  );
