import {createContext, useContext, useEffect, useState} from "react";
import './useLoading.css'
import {FallingLines} from "react-loader-spinner";

const LoadingContext = createContext(0);
const LoadingSwitcherContext = createContext(undefined);

export function useLoading() {
    return useContext(LoadingContext);
}

export function useLoadingSwitcher() {
    return useContext(LoadingSwitcherContext);
}

export function LoadingProvider({children}) {
    const [showOverlay, setOverlay] = useState(0);

    return <LoadingContext.Provider value={showOverlay}>
        <LoadingSwitcherContext.Provider value={v => setOverlay(v)}>
            <div style={{position: 'relative'}}>
                {children}
                <LoadingOverLay/>
            </div>
        </LoadingSwitcherContext.Provider>
    </LoadingContext.Provider>
}

function LoadingOverLay() {
    const showOverlay = useLoading()
    const [realShow, setRealShow] = useState(showOverlay)

    useEffect(() => {
        if (showOverlay === 0) {
            setRealShow(showOverlay)
            return
        }

        const timer = setTimeout(() => {
            setRealShow(showOverlay)
        }, 100)
        return () => clearTimeout(timer)
    }, [showOverlay]);

    if (realShow) {
        return <div className="overlayBG" style={{position: realShow === 1 ? 'absolute' : 'fixed'}}>
            <div className="overlayContent" onClick={(e) => {
                e.stopPropagation()
            }}>
                <FallingLines/>
            </div>
        </div>
    } else {
        return <></>
    }
}
