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

import { getPlayersAction, playersAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getPublisherIdsSelector } from '@/modules/@common/user/redux/selectors';

const queryGQL = `
  query getPublisherPlayers {
    getPublisherPlayers {
      results {
        id
        name
        alias
        publisherId
        urlPrefix
        displayEmbedCode
        videoObjectSupported
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getPlayersAction.type),
    filter(() => !!getPublisherIdsSelector(state$.value)?.length),
    switchMap(() => {
      const stream$ = gqlRequest({
        query: queryGQL,
      }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];

          if (!errors.length) {
            actions = [
              of(playersAction(data.getPublisherPlayers?.results.sort((a, b) => a?.alias?.localeCompare(b?.alias)))),
            ];
          }

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

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