/**
 * @file AuthMiddleware.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

import React, {useEffect, useState} from "react";
import {axiosGet, axiosPost, axiosSetAuthToken} from "./AxiosService";
import CenteredCircularProgress from "../components/common/CenteredCircularProgress";

const userContext = React.createContext(null);

const ProvideUserAuth = ({ children }) => {
    const [isLoading, setLoading] = useState(true);
    const provider = AuthProvider();

    useEffect(() => {
        axiosGet("/users/me")
            .then((res) => {
                provider.setUserAuth(res.data);
            })
            .catch((e) => {
                console.log("ProvideUser error: " + e);
            })
            .finally(() => {
               setLoading(false);
            });
    }, []);

    if (isLoading) {
        return <CenteredCircularProgress/>
    }
    return (
        <userContext.Provider value={provider}>
            {children}
        </userContext.Provider>
    );
}

const AuthProvider = () => {
    const [user, setUser] = useState(null);

    const login = (data, fok, fuk) => {
        axiosPost("/login", data).then((res) => {
            axiosSetAuthToken(res.data.token);
            axiosGet("/users/me").then((usr) => {
                setUser(usr.data);
                fok();
            })
            .catch((e) => {
                console.error(e);
                logout(fuk);
            });
        })
        .catch((e) => {
            console.error(e);
            logout(fuk);
        });
    }

    const logout = (fce) => {
        setUser(null);
        axiosSetAuthToken(null);
        axiosPost("/logout").then().catch();
        fce();
    }

    const setUserAuth = (data) => {
        setUser(data);
    }

    return {
         user,
         login,
         logout,
         setUserAuth
    }
}

const useAuth = () => {
    return React.useContext(userContext);
}

export {
    ProvideUserAuth,
    useAuth
}