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

import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { fetchPlayerConfigAction, setPlayerConfigAction } from '../slices';
import { getDirtyEvalObjectFromString, getPlayerConfigCdnEndpoint } from '@/modules/@common/PlayerWidget/helpers';
import { parseErrorMessage } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$) =>
  action$.pipe(
    ofType(fetchPlayerConfigAction.type),
    switchMap(({ payload }) => {
      const { player, publishers } = payload;

      const playerConfigRequest = ajax({
        url: getPlayerConfigCdnEndpoint(publishers, player),
        responseType: 'text',
        crossDomain: true,
        withCredentials: false,
      }).pipe(
        switchMap(({ response }) => of(setPlayerConfigAction(getDirtyEvalObjectFromString(response)))),
        catchError((error) => {
          const errorMessage = parseErrorMessage(error[0]);

          return of(
            showNotificationAction({
              type: TYPE_ERROR,
              message: errorMessage,
            }),
          );
        }),
      );

      return concat(playerConfigRequest);
    }),
  );
