import React from 'react'
import { StaticContext } from 'react-router'
import { Route, Redirect, RouteComponentProps } from 'react-router-dom'
import { Role, Permission, hasPermission, isInRole } from '../../utils/permissions'
import { getUserToken } from '../../utils/storage'

type PrivateRouteProps = {
    roles: Role[] | Role
    permission?: Permission
    component?: React.ComponentType<any> | React.ComponentType<RouteComponentProps<any, StaticContext, unknown>>
    children?: React.ReactNode
    [other: string]: any
}

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

    return (
        <Route {...other}
            component={available ? component : undefined}
            render={({ location }) => available ? children : (
                <Redirect to={{ pathname: '/login', state: { from: location } }} />
            )}
        />
    )
}
