"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const lib_1 = require("../../lib");
const components_1 = require("@bluebase/components");
const react_1 = tslib_1.__importDefault(require("react"));
const path_to_regexp_1 = require("path-to-regexp");
const lodash_get_1 = tslib_1.__importDefault(require("lodash.get"));
const core_1 = require("@bluebase/core");
exports.ModalNavigator = (props) => {
    const { children, initialRouteName, routes } = props;
    const location = lib_1.useLocation();
    const { navigate } = core_1.useNavigation();
    // Find initial route
    const currentIndex = routes.findIndex((route) => {
        const toPath = path_to_regexp_1.compile(route.path);
        return toPath(lodash_get_1.default(location, 'state', {})) === location.pathname;
    });
    const initialRouteIndex = initialRouteName
        ? routes.findIndex((route) => route.name === initialRouteName)
        : 0;
    const initialRoute = routes[initialRouteIndex];
    const isInitialRoute = currentIndex === initialRouteIndex;
    const initialRouteLocation = {
        pathname: initialRoute.path,
        search: '',
        hash: '',
        state: {},
    };
    if (isInitialRoute ||
        location.pathname.startsWith(path_to_regexp_1.compile(initialRouteLocation.pathname)(location.state))) {
        return children;
    }
    // Find refferer
    const referrer = lodash_get_1.default(location, 'state.__referrer');
    const background = referrer && referrer.pathname.startsWith(routes[initialRouteIndex].path)
        ? referrer
        : initialRouteLocation;
    const onDismiss = () => navigate({ path: referrer.pathname, params: referrer.state });
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(lib_1.Switch, { location: background }, children),
        react_1.default.createElement(components_1.Dialog, { visible: true, dismissable: true, onDismiss: onDismiss }, children)));
};
exports.ModalNavigator.displayName = 'ModalNavigator';
