import {GlobalVariable} from "@gongt/ts-stl-library/pattern/global-page-data";
import {Provider, ProviderProps} from "react-redux";
import {ReactRender} from "../react/render";
import {REDUX_PRELOAD_NAME} from "../redux/store";

export function reactUseRedux(react: ReactRender) {
	const preventDuplicate = new GlobalVariable(react);
	if (preventDuplicate.has('redux')) {
		throw new TypeError('reactUseRedux(): duplicate call to one react instance.')
	}
	preventDuplicate.set('redux', true);
	
	react.wrapComponent<ProviderProps>('Provider', Provider, (global: GlobalVariable) => {
		const store = global.get(REDUX_PRELOAD_NAME);
		if (!store || typeof store.getState !== 'function') {
			throw new Error('render react: REDUX is used, but has not been init.');
		}
		return {
			store: store,
		};
	});
}
