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

import { UPLOAD_FLOW_CREATE_VIDEO_VERSION } from '../../../constants';

import { titleSelector, videoSelector } from '../../selectors';
import {
  addToUploadQueueAction,
  clearAction,
  setS3LinksAction,
  startUploadFromQueueAction,
  startVideoVersionUploadAction,
} from '../../slices';
import { gqlRequest } from '@/modules/@common/request';
import { selectedVideoSelector } from '@/modules/editorial/editorialVideoDetails/redux/selectors';

const queryGQL = `
  query Query(
    $name: String,
    $filename: String,
    $contentOwnerId: Float!
  ) {
    S3UploadLink(
      name: $name,
      filename: $filename,
      contentOwnerId: $contentOwnerId
    ) {
      uploadUrl
      downloadUrl
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(startVideoVersionUploadAction.type),
    switchMap(() => {
      const video = videoSelector(state$.value);
      const title = titleSelector(state$.value);
      const selectedVideo = selectedVideoSelector(state$.value);

      const filename = video && video.name;
      const contentOwnerId = selectedVideo.contentOwner;

      const actions = [];

      if (filename) {
        const stream$ = gqlRequest({
          query: queryGQL,
          variables: {
            contentOwnerId,
            filename,
            name: title,
          },
        }).pipe(
          switchMap(({ data, errors }) => {
            const actions$ = [];

            if (!errors.length && data.S3UploadLink) {
              const s3uploadParams = { ...data.S3UploadLink };

              actions$.push(
                of(
                  setS3LinksAction({
                    key: 'uploadVideo',
                    s3uploadParams,
                  }),
                ),
              );
            }

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

        actions.push(stream$);
      }

      return concat(
        ...actions,
        of(addToUploadQueueAction()),
        of(clearAction()),
        of(startUploadFromQueueAction(UPLOAD_FLOW_CREATE_VIDEO_VERSION)),
      );
    }),
  );
