import {createContext, useContext, useReducer} from "react";

const AuthContext = createContext(undefined);
const AuthDispatchContext = createContext(null);

export function useAuth() {
    return useContext(AuthContext);
}

export function useAuthDispatch() {
    return useContext(AuthDispatchContext);
}

export function KeycloakContextProvider({children}) {
    const [auth, dispatch] = useReducer(authReducer, initialAuth);

    return <AuthContext.Provider value={auth}>
        <AuthDispatchContext.Provider value={dispatch}>
            {children}
        </AuthDispatchContext.Provider>
    </AuthContext.Provider>
}

function authReducer(auth, action) {
    switch (action.type) {
        case 'init': {
            return {
                is_authenticated: action.val.state,
                userinfo: action.val.userinfo
            }
        }
        case 'update': {
            return {
                ...auth,
                is_authenticated: action.val.state,
                userinfo: action.val.userinfo
                // data: {realm_access: {roles: ["federation_admin"]}}
                // data: JSON.parse(atob(action.token.split('.')[1]))
            }
        }
        case 'invalidate': {
            return {
                ...auth,
                is_authenticated: false
            }
        }
        default: {
            throw Error('Unknown action: ' + action.type);
        }
    }
}

const initialAuth = {
    is_authenticated: undefined,
    userinfo: undefined,
}