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

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

import { getPublisherPlayersAction, updateLiveEventFormAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

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

export default (action$) =>
  action$.pipe(
    ofType(getPublisherPlayersAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          ...action.payload,
          type: TYPE_LIVE,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const players = data.getLiveEventPublisherPlayers.results.sort((a, b) => a?.alias?.localeCompare(b?.alias));

            actions.push(
              of(
                updateLiveEventFormAction({
                  players,
                }),
              ),
            );
          }

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

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