import PropTypes from 'prop-types';

import { withSite } from '../../addons/Site';
import createItemComponent, {
  propTypes as ItemPropTypes,
} from './createItemComponent';

const propTypes = {
  /** Function to call with loaded link post or term. */
  children: PropTypes.func,

  /** ID of post to load. */
  id: ItemPropTypes.id,

  /** The post or item if already available. */
  item: PropTypes.object.isRequired,

  /** Slug of post to load. */
  itemSlug: ItemPropTypes.itemSlug,

  /** The name of the link to extract */
  link: PropTypes.string.isRequired,

  /** Content to display while awaiting data. */
  placeholder: ItemPropTypes.placeholder,

  /** Slug for post type from which posts are drawn. */
  typeSlug: ItemPropTypes.typeSlug,

  /**
   * StoryShare `Site`.
   * @private
   */
  site: PropTypes.object.isRequired,
};

/**
 * Item link
 * @param {Object} props - React component props.
 * @returns {Object} React element.
 */
export const ItemLink = ({ children, item, link, site }) => {
  const itemLinkUrl = site.objectToResponse(item).link(link);

  if (!itemLinkUrl) {
    return null;
  }

  return children(itemLinkUrl);
};

ItemLink.propTypes = propTypes;

export default withSite(createItemComponent()(ItemLink));
