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

import { getViewersCounterAction, updateLiveEventFormAction } from '../slices';
import { getToken } from '@/modules/@common/token/helpers';
import { idSelector, playerConfigSelector } from '@/modules/liveEvents/liveEvent/redux/selectors';

export default (action$, state$) =>
  action$.pipe(
    ofType(getViewersCounterAction.type),
    switchMap(() => {
      const playerConfig = playerConfigSelector(state$.value);
      const id = idSelector(state$.value);

      const params = {
        widgetId: playerConfig.widgetId,
        leid: id,
      };

      const stream$ = defer(() =>
        ajax({
          method: 'POST',
          url: '/api/trafficmanager/api/v3/player/live/counter',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            Authorization: getToken() || '',
          },
          crossDomain: true,
          withCredentials: true,
          body: JSON.stringify({
            ...params,
          }),
        }),
      ).pipe(
        switchMap(({ response }) =>
          of(
            updateLiveEventFormAction({
              viewersAmount: response?.viewersAmount,
            }),
          ),
        ),
        catchError(() => EMPTY),
      );

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