import * as React from "react";
import {logger} from "../lib/DefaultLogger";
import {userClient} from "../lib/clients/UserClient";
import {tokenUtil} from "../lib/TokenUtil";
import {createContext, useCallback, useEffect, useState} from "react";
import {api} from "../lib/clients/api";
import {requests} from "../requests";

export const UserContext = createContext(undefined);

export function UserProvider({children}) {
    const refresh = () => {
        checkSession()
            .catch((err) => logger.error(err))
    }
    const [state, setState] = useState({
        user: {},
        session: {},
        error: "",
        isLoading: true,
        refresh: refresh
    });

    const checkSession = useCallback(async () => {
        try {
            setState((prev) => ({...prev, isLoading: true}));
            if (!await tokenUtil.checkToken(tokenUtil.getToken())) {
                setState((prev) => ({...prev, error: '', isLoading: false, user: {}}));
                return;
            }
            api().get(requests.bar.session.status)
                .then((r) => setState((prevState) => ({
                    ...prevState,
                    session: r.data
                })))
                .catch(() => setState((prevState) => ({
                    ...prevState,
                    session: {}
                })))
            if (Object.keys(state.user).length === 0) {
                const {data, errorData} = await userClient.getMe();
                if (errorData) {
                    setState((prev) => ({...prev, error: errorData, isLoading: false, user: {}}));
                    return;
                }
                setState((prev) => ({...prev, error: "", isLoading: false, user: data}));
            }
        } catch (err) {
            logger.error(err);
            setState((prev) => ({...prev, error: 'Что-то пошло не так', isLoading: false, user: {}}));
        }
    }, [state]);

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

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

export const UserConsumer = UserContext.Consumer;

