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

import { getCurrentUploadStateFromQueue } from '../../selectors';
import { chooseVideoVersionUploadBranchAction, createVideoVersionAction, uploadVideoVersionAction } from '../../slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(chooseVideoVersionUploadBranchAction.type),
    switchMap(() => {
      const {
        video,
        videoUrl,

        uploadVideo,
      } = getCurrentUploadStateFromQueue(state$.value);

      const actions = [];

      if (video) {
        actions.push(of(uploadVideoVersionAction(uploadVideo)));
      } else if (videoUrl) {
        actions.push(of(createVideoVersionAction()));
      }

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