import * as React from 'react';
import {useCallback, useEffect} from 'react';
import {logger} from "../lib/DefaultLogger";
import {tokenUtil} from "../lib/clients/TokenUtil";

export const AuthContext = React.createContext(undefined);

export function AuthProvider({children}) {
    const [state, setState] = React.useState({
        auth: false,
        error: "",
        isLoading: true,
    });

    const checkSession = useCallback(async () => {
        try {
            if (!await tokenUtil.checkToken(tokenUtil.getToken())) {
                setState((prev) => ({...prev, auth: false, error: '', isLoading: false}));
                return;
            }
            setState((prev) => ({...prev, auth: true, error: "", isLoading: false}));
        } catch (err) {
            logger.error(err);
            setState((prev) => ({...prev, auth: false, error: 'Что-то пошло не так', isLoading: false}));
        }
        updater().then();
        // eslint-disable-next-line
    }, []);

    useEffect(() => {
        checkSession()
            .catch((err) => {
                logger.error(err);
            });
        // eslint-disable-next-line
    }, []);

    const updater = async () => {
        await new Promise((resolve) => setTimeout(resolve, 1000 * 60 * 60));
        checkSession()
            .catch((err) => {
                logger.error(err)
            })
    }

    return <AuthContext.Provider value={{...state}}>{children}</AuthContext.Provider>;
}

export const AuthConsumer = AuthContext.Consumer;
