import {promiseWorker,actionPromise} from "./promiseReducer";
import {gql} from "../actions";
import {takeEvery, call} from 'redux-saga/effects';
import {queries} from "../actions";
import {connect}   from 'react-redux';
import {Route, Redirect} from 'react-router-dom';
import {useEffect} from "react";

export function routeReducer(state={}, {type, match}) {
    if (type === 'ROUTE') {
        return match
    }
    return state
}

function* routeWorker({match}) {
    // console.log(match)
    if (match.path in queries) {
        const {name, query, variables} = queries[match.path](match)
        yield call(promiseWorker, actionPromise(name, gql(query, variables)))
    }
}

export function* routeWatcher() {
    yield takeEvery('ROUTE', routeWorker)
}

const RRoute = ({ action, component:Component, ...routeProps}) => {
    const WrapperComponent = (componentProps) => {
        useEffect(() =>{
            action(componentProps.match)
        })
        return <Component {...componentProps} />
    }
    return <Route {...routeProps} component={WrapperComponent} />
}
export const CRRoute = connect(null, {action: match => ({type: 'ROUTE', match})})(RRoute)

const ProtectedRoute = ({ fallback='/',
                            roles=["admin"],
                            auth,
                            component:Component,
                            ...routeProps}) => {

    const WrapperComponent = (componentProps) => {
        let aclArr = auth?.payload?.sub?.acl
        if (!aclArr) {
            aclArr = ['anon']
        }
        let crossArr = [];
        for (const role of roles) {
            crossArr = [...crossArr, ...aclArr.filter(aclItem => aclItem === role)]
        }
        if (crossArr.length === 0) {
            return <Redirect to={fallback} />
        } else {
            return <Component {...componentProps} />
        }
    }
    return <CRRoute {...routeProps} component={WrapperComponent} />
}

export const CProtectedRoute = connect(state => ({auth: state.auth}))(ProtectedRoute)