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

import { getImageData } from '../../helpers/request';
import { setIsLoadingAction, slice, updateLiveEventImageAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query Query(
    $id: String!,
    $name: String!,
    $contentOwner: Int!,
    $url: String!
  ) {
    updateLiveEventImage(
      id: $id,
      name: $name,
      contentOwner: $contentOwner,
      url: $url
    ) {
      imageId
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateLiveEventImageAction.type),
    switchMap(() => {
      const data = getImageData(state$.value[slice.name]);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          ...data,
        },
      }).pipe(
        switchMap(() => {
          const actions = [of(setIsLoadingAction(false))];

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

      return concat(of(setIsLoadingAction(true)), stream$);
    }),
  );
