import React, { useMemo } from 'react';

/*
 *
 * Receive Props, transform them in ComponentProps and return
 * Component with ComponentProps
 *
 * onlyRenderIf: only render component if function returns true
 *
 * onlyUpdate: only update component if a prop in array changes
 *
 */

const prepareComponent = (usePrepareComponent, options) => Component => {
  const PrepareComponent = props => {
    const newProps = usePrepareComponent(props);
    let updateProps = [newProps];

    if (options && options.onlyUpdate) {
      // eslint-disable-next-line react/destructuring-assignment
      updateProps = options.onlyUpdate.map(item => props[item]);
    }

    const MemoizeComponent = useMemo(() => /*#__PURE__*/React.createElement(Component, newProps), // eslint-disable-next-line react-hooks/exhaustive-deps
    updateProps);

    if (options && options.onlyRenderIf && !options.onlyRenderIf(props)) {
      return null;
    }

    return MemoizeComponent;
  };

  return PrepareComponent;
};

export { prepareComponent as default };
