import { Route, Switch } from "wouter";
import inDev from "../utils/inDev";
import { RoutingTree } from "../types/routesTypes";
import { SwitchRouteGeneratorProps } from "../types/switchRouteGeneratorTypes";
import { clearMultiplePathSlashes } from "../utils/StringTransformationUtils";

const routesCrawler = (
	routesTree: RoutingTree,
	parentPath?: string,
): JSX.Element[] => {
	return routesTree.map((route): JSX.Element => {
		// -----
		if (route.path) {
			const _path = clearMultiplePathSlashes(
				parentPath && parentPath !== "/" ? parentPath + route.path : route.path,
			);
			// Debug log shows generated routes
			inDev(() => console.log("routesCrawler_routes", route.name, _path));
			// -----
			if (route.nest) {
				return (
					<Route key={_path} path={_path}>
						<Switch key={`${route.name}_switch_route`}>
							{routesCrawler(route.nest, _path)}
						</Switch>
					</Route>
				);
			} else return <Route key={_path} path={_path} component={route.component} />;
		} else return <Route key={route.name} component={route.component} />;
	});
};

/**
 * This component is used to generate Switch with Routes for given routes object
 */
const SwitchRouteGenerator = ({ routesTree }: SwitchRouteGeneratorProps) => {
	return <Switch key={"main_switch_route"}>{routesCrawler(routesTree)}</Switch>;
};
export default SwitchRouteGenerator;
