import classNames from 'classnames';
import React, { PropTypes } from 'react';

/**
 * Render a code block
 * @param {Object} props - The component properties
 * @param {boolean?} props.instructionBlock - is this code block an instruction block?
 * @param {string?} props.extraClasses - any extra CSS classes
 * @param {string?} props.code - a string to be used as the code block
 * @param {ReactElement|HTMLElement|string?} props.children - the content of the code block.
 *        This can be a string or a set of <line>s. If a set of <line>s is provided the will be
 *        rendered line by line and whitespace in them will remain intact.
 * @returns {ReactElement}
 * @constructor
 */
const Codeblock = props => {
    return (
        <div
            className={classNames(
                'code-block',
                {
                    'instruction-block': props.instructionBlock,
                },
                props.extraClasses
            )}
        >
            <pre>
                <code>
                    {props.code || renderChildrenLines(props.children)}
                </code>
            </pre>
        </div>
    );
};

Codeblock.propTypes = {
    instructionBlock: PropTypes.bool,
    extraClasses: PropTypes.string,
    children: PropTypes.node,
    code: PropTypes.string,
};

function renderChildrenLines(children) {
    return React.Children.map(children, child => {
        // if there is a <line> element, return its children with a newline
        return child.type && child.type.toLowerCase() === 'line' && [child.props.children, '\n'] || child;
    });
}
export default Codeblock;
