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

import { videoSelector } from '../selectors';
import { monitoringStartAction, videoJobAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { selectedVideoSelector } from '@/modules/editorial/editorialVideoDetails/redux/selectors';

const queryGQL = `
  mutation VideoJobMutation(
    $videoId: String!,
    $job: String!,
    $timestamp: Int,
    $url: String,
    $speechModel: String,
  ) {
    videoJob(
      videoId: $videoId,
      job: $job,
      timestamp: $timestamp, 
      url: $url,
      speechModel: $speechModel,
    )
  }
`;

const monitoringEpic = (action$, state$) =>
  action$.pipe(
    ofType(videoJobAction.type),
    switchMap((action) => {
      const { jobType, timestamp, url, video, speechModel } = action.payload;

      const state = state$.value;
      const selectedVideo = videoSelector(state) || video || selectedVideoSelector(state);
      const { uid } = selectedVideo;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: uid,
          job: jobType,
          timestamp,
          url,
          speechModel,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          if (!errors.length && data.videoJob === true) {
            actions.push(concat(of(monitoringStartAction())));
          }

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

      return concat(stream$);
    }),
  );

export default monitoringEpic;
