/* eslint-disable @typescript-eslint/no-var-requires */
import * as React from 'react';
import { useSelector } from "react-redux";
import { Route, Routes, Navigate } from "react-router-dom";
import NotFound from "components/basic/NotFound";
import { RootState } from 'store/store';
import { RouterApi } from "./types";

const projectConfig = require("configure/projectConfig.json");

export const convertRouter = (
  routers: RouterApi.RouterItem[],
  parentPath = ""
) => {
  const user = useSelector((state: RootState) => state.user);
  const authList = user.auth || [];

  const result: Array<object> = [];
  routers.forEach((routerItem: RouterApi.RouterItem) => {
    const itemPath = `${parentPath}${routerItem.path}`;
    const childRouter = {
      ...routerItem,
      path: itemPath,
      parentPath,
    };
    const { children, auth } = routerItem;
    if (children && children.length) {
      if (
        authList.some((_authItem: string) =>
          _authItem.startsWith(auth as string)
        ) ||
        projectConfig.noAuth ||
        auth === "all"
      ) {
        result.push(childRouter);
      }
      result.splice(
        result.length - 1,
        0,
        ...convertRouter(children, itemPath)
      );
    } else if (
      authList.includes(auth as string) ||
      projectConfig.noAuth ||
      auth === "all"
    ) {
      result.push(childRouter);
    }

    return result;
  });

  return result;
};

export const listRouterToComponent = (routes: RouterApi.RouterItem[]) => (
  <Routes>
    {[
      ...convertRouter(routes, "").map((route: RouterApi.RouterItem) => {
        const { path, Component } = route;
        return <Route path={path} key={path} element={<Component />} />;
      }),
    ]}
    <Route key="404" path="/404" element={<NotFound />} />
    {projectConfig.homepage.map((homepageItem: string) => (
      <Route key="/" path="/" element={<Navigate replace to={homepageItem} />} />
    ))}
  </Routes>
);
