import * as React from 'react';
import storage from '../utils/storage';
import {
	Route,
	BrowserRouter as Router,
	Switch,
	Redirect,
	RouteProps,
} from 'react-router-dom';
import { routerConfig } from './config';
interface Iprops {
	isAdmin?: boolean;
}
const router: React.FC<Iprops> = ({ isAdmin = false }) => {
	return (
		<Router>
			<Switch>
				{routerConfig.map((route) => {
					if (route.routes) {
						if (route.admin && !isAdmin) {
							return (
								<Route
									key={route.path}
									path={route.path}
									exact={!!route.exact}
									render={() => {
										return <Redirect to='/'></Redirect>;
									}}></Route>
							);
						}
						return (
							<Route
								key={route.path}
								path={route.path}
								exact={!!route.exact}
								render={(props) => {
									const sessionToken = sessionStorage.getItem('token');
									const { value, sucess } = storage.getItme('token');
									if (!!sessionToken || sucess) {
										return (
											<route.component
												{...props}
												routes={route.routes}></route.component>
										);
									}
									return <Redirect to='/login'></Redirect>;
								}}></Route>
						);
					}
					return (
						<Route
							key={route.path}
							path={route.path}
							exact={route.exact}
							component={route.component}></Route>
					);
				})}
			</Switch>
		</Router>
	);
};
export default router;
