import { HashRouter as Router, Switch, Redirect, Route } from "react-router-dom"
import React, { Fragment } from "react"

import Auth from "./Auth"
import routes, { Loading } from "./route"

function LoadWrapper(props: any) {
    if (props.isLazy) {
        const LoadingComp = props.loading ? props.loading : () => <Loading></Loading> //NormalLoading;
        return <React.Suspense fallback={<LoadingComp></LoadingComp>}>{props.children}</React.Suspense>
    }
    return <Fragment>{props.children}</Fragment>
}

function RouteMap(props: any) {
    const routes: any[] = props.routes

    return (
        <Switch>
            {routes.map((route, index) => {
                const { exact = false } = route
                const isAuth = !!route.meta?.auth
                if (route.redirect) {
                    return (
                        <Auth key={index} needAuth={isAuth} path={route.path} exact={exact}>
                            <Route key={index} path={route.path} exact={exact}>
                                <Redirect to={route.redirect}></Redirect>
                            </Route>
                        </Auth>
                    )
                }
                if (route.component) {
                    return (
                        <Auth key={index} needAuth={isAuth} path={route.path} exact={exact}>
                            <LoadWrapper loading={route.loading} isLazy={typeof route.component.$$typeof === "symbol"}>
                                <route.component meta={route.meta}>
                                    {route.children && <RouteMap routes={route.children}></RouteMap>}
                                </route.component>
                            </LoadWrapper>
                        </Auth>
                    )
                }
            })}
        </Switch>
    )
}

export default function AppRouter() {
    return (
        <Router>
            <RouteMap routes={routes}></RouteMap>
        </Router>
    )
}