import React, { createContext, useCallback, useContext } from "react";

const RefreshContext = createContext(null as any);

export function useRefresh() {
	return useContext(RefreshContext);
}

export default function RefreshScope({ update, children }: any) {
	const originalUpdate = useRefresh();
	
	const _update = useCallback(async function(maxDepth?: number) {
		if (maxDepth === 0)
			return;
		
		const nextDepth = (maxDepth || 0) - 1;
		
		await Promise.all([
			update && update(),
			originalUpdate && originalUpdate(nextDepth)
		]);
	}, [update, originalUpdate]);
	
	return <RefreshContext.Provider value={_update}>
		{ children }
	</RefreshContext.Provider>;
}
