import { FC, ReactNode } from 'react'
import { Location } from 'history'
import { Redirect, Route, RouteProps } from 'react-router-dom'

import { Role, Permission, hasPermission, isInRole } from '../../utils/permissions'
import { getUserToken } from '../../utils/storage'

export type PrivateRouteProps = RouteProps & {
    roles: Role[] | Role
    permission?: Permission
    children?: ReactNode
    redirect?: (location?: Location<unknown>) => ReactNode
}

export const defaultRedirect = (location?: Location<unknown>) => (
    <Redirect to={{ pathname: '/login', state: { from: location } }} />
)

export const PrivateRoute: FC<PrivateRouteProps> = ({ permission, roles, component, children, redirect = defaultRedirect, ...other }) => {
    const available = getUserToken() && (hasPermission(permission) && isInRole(roles))

    return (
        <Route {...other}
            component={available ? component : undefined}
            render={({ location }) => available ? children : redirect(location)}
        />
    )
}

export default PrivateRoute
