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

import * as selectors from '../selectors';
import { getPlayerOptionsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getFormPublisherPlayers($publisherId: Int) {
    getFormPublisherPlayers(publisherId: $publisherId) {
      results {
        id
        name
        playerAspectRatio
        type
      }
    }
  }
`;

const getResponse = ({
  data: {
    getFormPublisherPlayers: { results: players },
  },
}) =>
  players.map((player) => ({
    value: player.id,
    label: player.name,
    playerAspectRatio: player.playerAspectRatio,
  }));

export default (action$, state$) =>
  action$.pipe(
    ofType(getPlayerOptionsAction.type),
    switchMap(() => {
      const state = state$.value;
      const autocomplete = selectors.autocompleteSelector(state);
      const site = selectors.siteSelector(state);

      const stream$ = gqlRequest({
        query,
        variables: {
          publisherId: site.value,
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            actions.push(
              of(
                setFieldAction({
                  autocomplete: {
                    ...autocomplete,
                    textOptions: getResponse(response),
                  },
                }),
              ),
            );
          }

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

      return concat(
        of(
          setFieldAction({
            autocomplete: {
              ...autocomplete,
              textOptions: null,
            },
          }),
        ),
        stream$,
      );
    }),
  );
