import PropTypes from 'prop-types';
import { addIndex, map } from 'ramda';
import React from 'react';

import blockComponents from './blocks';

/* Interface */
const propTypes = {
  /**
   * Blocks to render
   * Returned with a post as `content.blocks`.
   */
  blocks: PropTypes.arrayOf(
    PropTypes.shape({
      name: PropTypes.string.isRequired,
      attributes: PropTypes.object.isRequired,
    }),
  ).isRequired,
};

/**
 * Renders content created using the admin panel block editor
 * @param {Object} props - React component props.
 * @returns {Object} React element.
 */
export const BlockContent = ({ blocks }) => (
  <>
    { addIndex(map)((block, index) => {
      // Unpack the block object and find which component to use
      const { name, attributes } = block;
      const Block = blockComponents[name];
      if (!Block) {
        return null;
      }

      return <Block key={ index } { ...attributes } />;
    }, blocks) }
  </>
);

BlockContent.propTypes = propTypes;

export default BlockContent;
