import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { Role, Permissions, hasAccess } from '../../utils/permissions'

type PrivateRouteProps = {
    permissions?: Permissions
    roles: Role[]
    component?: any
    children?: any
    [other: string]: any
}

export const PrivateRoute: React.FC<PrivateRouteProps> = ({ permissions, roles, component, children, ...other }) => {
    const available = localStorage['token'] && hasAccess({ permissions, roles })

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