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

import GenericFormat from '../formats/GenericFormat';

/* Interface */
const propTypes = {
  /** Children to render */
  children: PropTypes.array.isRequired,
};

/**
 * Renders content produced by Gutenberg's `<RichText>` editor
 * Raw HTML content should be converted to `children` using the
 * `childrenFromHtml()` function.
 * @private
 * @param {Object} props - React component props.
 * @returns {Object} React element.
 */
export const RichText = ({ children }) => (
  <>
    { addIndex(map)((child, index) => {
      // Children is an array of `WPBlockNode` text strings and objects.
      // Handle the strings first
      if (typeof child === 'string') {
        return child;
      }

      if (typeof child !== 'object') {
        return null;
      }

      const { type, props } = child;

      return (
        <GenericFormat
          key={ index }
          type={ type }
          RichText={ RichText }
          { ...props }
        />
      );
    }, children) }
  </>
);

RichText.propTypes = propTypes;

export default RichText;
