import { Middleware, route } from "@/routing";
import { useSelector } from "react-redux";
import { AppState, isReady } from "@/state/reducer";
import { Redirect } from "react-router-dom";
import React from "react";
import { UserState } from "@/state/reducer/user";

export const isReadyMiddleware: Middleware<any, any> = next => isLoggedInMiddleware(() => {
    const ready = useSelector(isReady);

    if (ready) {
        return <>{ next() }</>;
    }

    return <Redirect to={ route("edition_pick") } />;
})

export const isLoggedInMiddleware: Middleware<any, any> = next => {
    const user = useSelector<AppState>(state => state.user) as UserState;

    if (user.loggedIn) {
        return <>{ next() }</>;
    }

    return <Redirect to={ route("user_login") } />;
}
