import { Route, Router, Switch } from "react-router-dom";
import { History } from "history";
import { Suspense, useEffect, useState } from "react";
import LoadingComponent from "../../../common/LoadingComponent";
import { IRouteRule } from "../Menu/types";
import { UserInfoContext } from "./context/UserInfoContext";
import { UserInfo } from "./services/interface";
import { getUserInfo } from "./services";

import menu from "./menu";
import routes from "./routes";

interface SaturnAppProps {
  history: History;
}

interface SaturnRouteRule extends IRouteRule {
  props: Record<string, any>;
}

export const saturnMenu = menu;
export const saturnRoutes = routes;

function SaturnApp({ history }: SaturnAppProps) {
  const [userInfo, setUserInfo] = useState<UserInfo>();
  useEffect(() => {
    getUserInfo().then((res) => {
      setUserInfo(res.data);
    });
  }, []);
  return (
    <UserInfoContext.Provider value={userInfo}>
      <Router history={history}>
        <Switch>
          {routes.map((route: SaturnRouteRule) => {
            return (
              <Route
                key={route.path}
                exact
                path={route.path}
                children={(routerProps) => (
                  <Suspense fallback={<LoadingComponent />}>
                    <route.component {...routerProps} {...route.props} />
                  </Suspense>
                )}
              />
            );
          })}
        </Switch>
      </Router>
    </UserInfoContext.Provider>
  );
}

export default SaturnApp;
