import {connect} from "react-redux";
import {Redirect} from "react-router-dom";
import Route from "react-router-dom/es/Route";

const RRoute = ({action, component:Component,...routeProps}) => {
    const WrapperComponent = (componentProps) => {
        action(componentProps.match)
        return <Component {...componentProps}/>
    }
    return <Route {...routeProps} component={WrapperComponent}/>
}

const CRRoute = connect(null, {action: match => ({type: 'ROUTE', match})})(RRoute)
const ProtectedRoute =({ fallback='/',
                         roles=['admin'],
                         auth,
                         component: Component,
                         ...routeProps}) => {
    const WrapperComponent = (componentProps) => {
        let acl = auth?.payload?.sub?.acl
        if (localStorage?.authToken && acl && Array.isArray(acl) && acl.length > 0) {
            acl = acl.filter(item => {
                if(roles.includes(item)) return item
            })
            if (acl.length > 0){
                return <Component {...componentProps}/>
            }
        }
        else if (localStorage?.authToken){
            return <Component {...componentProps}/>
        }
        return <Redirect to={fallback}/>
    }
    return <CRRoute {...routeProps} component={WrapperComponent}/>
}
export const CPRoute = connect(state=>({auth: state.auth}))(ProtectedRoute)
