import React from 'react';
import PropTypes from 'prop-types';
import { path } from 'ramda';

import formats from '../../formats';
import { withOptions } from '../../../../addons/Site';

/* Interface */
export const propTypes = {
  /** Content to render within this format */
  children: PropTypes.array.isRequired,

  /** Site options (can be used to override formats) */
  options: PropTypes.shape({
    blockContent: PropTypes.shape({
      formats: PropTypes.object,
    }),
  }),

  /**
   * RichText component
   * We can't import this directly as that would lead to a dependency cycle
   * so we pass as a prop instead.
   */
  RichText: PropTypes.func.isRequired,

  /** Type of format to render */
  type: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired,
};

/**
 * Renders component for each type rendered in `<RichText>` component
 * @private
 * @param {Object} props - React component props.
 * @returns {Object} React element.
 */
export const GenericFormat = ({
  children,
  type,
  RichText,
  options,
  ...passThroughProps
}) => {
  // Assemble all permitted formats by merging with options
  const allFormats = {
    ...formats,
    ...(path(['blockContent', 'formats'], options) || { }),
  };

  const Component = allFormats[type] || type;

  return (
    <Component { ...passThroughProps }>
      <RichText>
        { children }
      </RichText>
    </Component>
  );
};

GenericFormat.propTypes = propTypes;

export default withOptions(GenericFormat);
