"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const components_1 = require("@bluebase/components");
const core_1 = require("@bluebase/core");
const react_1 = tslib_1.__importStar(require("react"));
const react_router_1 = require("react-router");
const helpers_1 = require("../../helpers");
const Navigation_1 = require("../Navigation");
const navigators_1 = require("../../navigators");
exports.Navigator = (props) => {
    const { type, initialRouteName, routes } = props, rest = tslib_1.__rest(props, ["type", "initialRouteName", "routes"]);
    const mainNavigator = react_1.useContext(Navigation_1.MainNavigatorContext);
    const ScreenView = core_1.useComponent('ScreenView');
    const screenProps = helpers_1.useScreenProps();
    const NavigatorImpl = navigators_1.getNavigator(type);
    if (!NavigatorImpl) {
        return null;
    }
    // If routes is a thunk, resolve it
    const resolvedRoutes = core_1.resolveThunk(routes, screenProps) || [];
    /**
     * Render each indivitual route
     * @param route
     */
    const renderRoute = (route) => {
        const { exact, name, path } = route;
        return (react_1.default.createElement(react_router_1.Route, { key: name, exact: exact, path: path }, (routerProps) => {
            const navigation = helpers_1.historyToActionObject(routerProps, mainNavigator);
            return (react_1.default.createElement(core_1.NavigationContext.Provider, { value: navigation },
                react_1.default.createElement(ScreenView, { Layout: NavigatorImpl.Screen, navigator: props, route: route, navigation: navigation, options: helpers_1.resolveRouteOptions(route, props, mainNavigator, {
                        navigation,
                        screenProps,
                    }) }, route.navigator ? react_1.default.createElement(exports.Navigator, Object.assign({}, route.navigator)) : null)));
        }));
    };
    /**
     * Redirects to the initial route, if non is given redirects to the
     * first route in the routes array.
     */
    const renderInitialRoute = () => {
        if (resolvedRoutes.length === 0) {
            return null;
        }
        return (react_1.default.createElement(react_router_1.Route, null, (routerProps) => {
            const navigation = helpers_1.historyToActionObject(routerProps, mainNavigator);
            return (react_1.default.createElement(components_1.Redirect, { routeName: initialRouteName || resolvedRoutes[0].name, params: navigation.state.params }));
        }));
    };
    return (react_1.default.createElement(NavigatorImpl.Navigator, Object.assign({}, props, { routes: resolvedRoutes }),
        react_1.default.createElement(react_router_1.Switch, Object.assign({}, rest),
            resolvedRoutes.map(renderRoute),
            renderInitialRoute())));
};
exports.Navigator.displayName = 'Navigator';
