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

import { PCN_POST_VIDEO } from '@/modules/@common/acl/constants';

import { getCurrentUploadStateFromQueue } from '../../selectors';
import { chooseUploadBranchAction, createVideoAction, uploadCsvAction, uploadVideoAction } from '../../slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

export default (action$, state$) =>
  action$.pipe(
    ofType(chooseUploadBranchAction.type),
    filter(() => hasPermission(PCN_POST_VIDEO, getUserPermissionsSelector(state$.value))),
    switchMap(() => {
      const {
        csvFile,
        video,
        thumbnail,
        ccFiles,
        videoUrl,

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

      const actions = [];

      if (csvFile) {
        actions.push(of(uploadCsvAction(uploadCsv)));
      } else if (video || csvFile || thumbnail || ccFiles) {
        actions.push(of(uploadVideoAction(uploadVideo)));
      } else if (videoUrl) {
        actions.push(of(createVideoAction()));
      }

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