
import React, { createContext, useContext, useState } from 'react';
import Loading from '../components/common/Loading';

const LoadingContext = createContext();

export const LoadingProvider = ({ children }) => {
	const [isLoading, setIsLoading] = useState(false);

	const showLoading = () => setIsLoading(true);
	const hideLoading = () => setIsLoading(false);

	const withLoading = async (asyncFunction) => {
		const startTime = Date.now();
		showLoading();
		try {
			return await asyncFunction();
		} finally {
			const processTime = Date.now() - startTime;

			if(processTime < 1000){
				await new Promise(resolve => setTimeout(resolve, 500));
			}

			hideLoading();
		}
	};

	return (
		<LoadingContext.Provider value={{ isLoading, showLoading, hideLoading, withLoading }}>
			{children}
			{isLoading && <Loading />}
		</LoadingContext.Provider>
	);
};

export const useLoading = () => useContext(LoadingContext);