import React from 'react';
import {
    Route
} from 'react-router-dom';

/**
 * Provide endless cascading routing over configs and 1. with automatic subrendering, 2. with subrendering over passing subroutes to rendered component
 */
class RouteCascaded extends React.Component {
    render() {
        const {component, path, exact, routes, childComponent} = this.props;

        let Comp = null;
        if(component) {
            Comp = component;
        }

        return (
            <React.Fragment>{
                Comp ?
                    <Route
                        path={path}
                        exact={exact}
                        render={props => (
                            // pass the sub-routes down to keep nesting
                            <Comp {...props} routes={routes}/>
                        )}
                    /> : null
            }
                {(routes ?
                    // when there is a defined component name, add further cascading routing into render prop
                    routes.map((route, i) => (
                        route && route.hasOwnProperty(childComponent) && route[childComponent] ?
                            <RouteCascaded key={i}
                                           {...route}
                                           component={route[childComponent]}
                                           childComponent={childComponent}
                                           exact={exact}/>
                            : null))
                    : null)}
            </React.Fragment>
        );
    }
}

export default RouteCascaded;