import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { orderableComponentsShape } from '../../constants/components/prop-types/orderable-component';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/PageOrderableContainer.scss';

const n = createNamespace('PageOrderableContainer');

const isComponentNull = (Component, data) => {
    if (!Component) {
        return true;
    }

    let componentNull = false;
    const componentRequiredDataFunc = Component.schema().requiredDataFunc;
    if (componentRequiredDataFunc) {
        componentNull = !componentRequiredDataFunc(data);
    }
    return componentNull;
};

export const ChildrenOrderableContainer = ({ orderableComponents, componentsList }) => {
    // We wrap orderable component inside a div with the orderable component id
    // in order to have scroll to animation to the orderable component on preview.
    // Although, we define id on both div and component, only the id in div will
    // be generated.
    const withOrderableComponent = (Component, { id, data, settings, menus = {} }) => (
        !isComponentNull(Component, data) ? (
            <div {...n('childItem').withTestId().props} id={id} key={id}>
                {Component && <Component key={id} id={id} data={data} settings={settings} menus={menus} />}
            </div>
        ) : null
    );

    const renderOrderableComponents = components => (
        components.map(
            ({ id, name, data, settings, menus = {} }) => (
                withOrderableComponent(componentsList[name], { id, data, settings, menus })
            )
        )
    );

    return (
        <div {...n('container').withTestId().props}>
            {renderOrderableComponents(orderableComponents)}
        </div>
    );
};

ChildrenOrderableContainer.propTypes = {
    orderableComponents: PropTypes.arrayOf(orderableComponentsShape),
    componentsList: PropTypes.object
};

ChildrenOrderableContainer.defaultProps = {
    orderableComponents: [],
    componentsList: {}
};

export default ChildrenOrderableContainer;
