import * as React from 'react'
import { connect, DispatchProp } from 'react-redux'
import { Redirect, Route, RouteProps } from 'react-router-dom'

export interface IPrivateRouteProps extends RouteProps, DispatchProp<any> {
  isAuthenticated: boolean
  redirectTo?: string
}

const PrivateRoute: React.StatelessComponent<IPrivateRouteProps> = ({
  isAuthenticated,
  redirectTo = '/login',
  component,
  ...other,
}) => {
  if (isAuthenticated) {
    return <Route component={component} {...other} />
  } else {
    return <Redirect to={redirectTo} />
  }
}

export default connect((state: any) => ({
  isAuthenticated: !!state.auth.principal,
}))(PrivateRoute)
