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

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

import { getTmPlaylistAction, updateLiveEventFormAction } from '../slices';
import { getPlaylistApiEndpoint } from '@/modules/@common/PlayerWidget/helpers';
import { parseErrorMessage } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';
import { idSelector, playerConfigSelector } from '@/modules/liveEvents/liveEvent/redux/selectors';

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

      const params = {
        dev: 'desktop',
        publisherId: playerConfig.publisherId,
        widgetId: playerConfig.widgetId,
        session: `${Math.random()}`,
        url: `${window.location.href}`,
      };

      if (id) {
        params.leid = id;
      }
      const stream$ = defer(() =>
        ajax({
          method: 'POST',
          url: `${getPlaylistApiEndpoint()}`,
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          crossDomain: true,
          withCredentials: true,
          body: JSON.stringify({
            ...params,
          }),
        }),
      ).pipe(
        switchMap(({ response }) =>
          of(
            updateLiveEventFormAction({
              tmPlaylist: response,
            }),
          ),
        ),
        catchError(({ response }) => {
          const errorMessage = parseErrorMessage(response);

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

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