
// import react
import Api from '@craftiq/node';
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

// locals
import ApiSignal from '../signals/Api';

// create global query client
const queryClient = new QueryClient();

/**
 * api provider
 *
 * @param props 
 */
const ApiProvider = (props = {}) => {
  // create api
  if (!ApiSignal.get()) {
    // set new API
    ApiSignal.set(new Api({
      url       : props.apiUrl,
      user      : props.apiUser,
      token     : typeof props.token === 'function' ? props.token : null,
      client    : props.apiClient,
      version   : props.version,
      translate : props.translate,

      options : {
        query : {
          token : typeof props.token === 'function' ? null : props.token,
        },
      },
    }));
  } else {
    // update values
    ApiSignal.get().update({
      user   : props.apiUser,
      token  : typeof props.token === 'function' ? props.token : null,
      client : props.apiClient,
    });
  }

  // return children
  return (
    <QueryClientProvider client={queryClient}>
      {props.children}
    </QueryClientProvider>
  );
};

/**
 * export default
 */
export default ApiProvider;