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

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

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

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