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

import { getUiPropsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getPlayerUiProps(
    $forTable: Boolean
    ) {
    getPlayerUiProps(
    forTable:  $forTable
      ) {
      availableTemplatePlayers {
      id
      name
      order
      }
      embedSources {
        deOutstream
        dfpOutstream
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getUiPropsAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
        variables: {
          forTable: true,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const { availableTemplatePlayers: playerTypes, embedSources } = response.data.getPlayerUiProps;
            return of(
              setAction({
                typesOptions: playerTypes,
                embedSources,
              }),
            );
          }
          return EMPTY;
        }),
      );
      return stream$;
    }),
  );
