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

import { TYPE_LIVE } from '@/modules/@common/constants/playerTypes';

import { getPlayersAction, setPlayersAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';

const queryGQL = `
  query getLiveEventPublisherPlayers($type: Int!) {
    getLiveEventPublisherPlayers(type: $type){
      results {
        id
        name
        alias
        publisherId
        urlPrefix
        displayEmbedCode
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPlayersAction.type),
    debounceTime(500),
    filter(() => !!getToken()),
    switchMap(() => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          type: TYPE_LIVE,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const players = data.getLiveEventPublisherPlayers.results
              .map((player) => ({
                id: player.id,
                name: player.alias || player.name,
              }))
              .sort((a, b) => a?.name?.localeCompare(b?.name));

            actions.push(of(setPlayersAction(players)));
          }

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

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