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

import {
  CANCEL_UPLOAD_LOGIN_AS,
  CANCEL_UPLOAD_LOGOUT,
  CANCEL_UPLOAD_PROGRESS_UPLOAD,
  UPLOAD_STATUS_CANCELED,
} from '@/modules/uploaderNew/constants';

import { uploadConfirmDialogSelector } from '../selectors';
import {
  clearUploadQueueAction,
  handleCancelUploadFromConfirmDialogAction,
  hideCancelUploadConfirmDialogAction,
  loadingProgressAction,
  setProcessUploadStatusAction,
  startUploadFromQueueAction,
  uploadVideoCancelledAction,
} from '../slices';
import { cancelImpersonationAction, logOutEventAction } from '@/modules/@common/token/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(handleCancelUploadFromConfirmDialogAction.type),
    switchMap(() => {
      const uploadConfirmDialog = uploadConfirmDialogSelector(state$.value);
      const actions = [];

      // from upload status
      if (uploadConfirmDialog.context === CANCEL_UPLOAD_PROGRESS_UPLOAD) {
        if (uploadConfirmDialog?.processedUploadQueueId) {
          const { processedUploadQueueId } = uploadConfirmDialog;
          actions.push(
            of(uploadVideoCancelledAction({ processedUploadQueueId })),
            of(setProcessUploadStatusAction({ processedUploadQueueId, status: UPLOAD_STATUS_CANCELED })),
            of(loadingProgressAction({ percentage: 0, processedUploadQueueId })),
            of(startUploadFromQueueAction()),
          );
        } else {
          actions.push(of(clearUploadQueueAction()));
        }
      }

      // from login as
      if (uploadConfirmDialog.context === CANCEL_UPLOAD_LOGIN_AS) {
        actions.push(of(clearUploadQueueAction()), of(cancelImpersonationAction()));
      }

      // from logout
      if (uploadConfirmDialog.context === CANCEL_UPLOAD_LOGOUT) {
        actions.push(of(clearUploadQueueAction()), of(logOutEventAction()));
      }

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