import { Middleware, route } from "@/routing";
import { useSelector } from "react-redux";
import { AppState, isReady } from "@/state/reducer";
import { Redirect, useRouteMatch } from "react-router-dom";
import React, { useEffect } 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 />;
    }

    window.sessionStorage.setItem('back-path', window.location.pathname);

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