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

import { getPlayerOptionsAction, getPlaylistsByUrlAction, setPlayerOptionsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';
import { getPublisherIdsSelector } from '@/modules/@common/user/redux/selectors';
import { urlSelector } from '@/modules/editorial/RightSideBar/TabPlaylist/Edit/redux/selectors';

const queryGQL = `
  query getPublisherPlayers($publisherIds: [Int]) {
    getPublisherPlayers(publisherIds: $publisherIds) {
      results {
        id
        name
        alias
        publisherId
        urlPrefix
        displayEmbedCode
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getPlayerOptionsAction.type),
    filter(() => !!getToken()),
    filter((action) => action?.payload || !!getPublisherIdsSelector(state$.value)?.length),
    switchMap((action) => {
      const variables = {};

      variables.publisherIds = [action.payload];

      const stream$ = gqlRequest({ query: queryGQL, variables }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

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

            actions.push(of(setPlayerOptionsAction(players)));

            const url = urlSelector(state$.value);
            if (url) {
              actions.push(of(getPlaylistsByUrlAction()));
            }
          }

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

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