import {GlobalContextProvider} from "@gongt/ts-stl-client/react/global-context";
import {
	debugComponent,
	debugComponentEnabled,
	REACT_ROOT_ELEMENT_ID_VARNAME,
	ReactRenderBase,
} from "@gongt/ts-stl-client/react/render";
import {GlobalVariable} from "@gongt/ts-stl-library/pattern/global-page-data";
import * as React from "react";
import {renderToString} from "react-dom/server";
import {HtmlContainer, IContainerPlugin, RenderContext} from "../middlewares/html-render";

// export function multiTickRender(render: RenderFunction): AsyncRenderFunction {
// }

export class ReactRender extends ReactRenderBase implements IContainerPlugin<{}> {
	__modify_html(html: HtmlContainer) {
		html.addBody(`<%- REACT_ROOT_HTML %>`);
		html.dynamic('ReactRender', (context: RenderContext) => {
			context.variables.REACT_ROOT_HTML = this.render(context.global);
		});
	}
	
	render(context: GlobalVariable = new GlobalVariable({})): string {
		const component = <GlobalContextProvider global={context}>
			{this.getComponent(context)}
		</GlobalContextProvider>;
		if (debugComponentEnabled) {
			debugComponent(component);
		}
		const str = renderToString(component);
		
		context.set(REACT_ROOT_ELEMENT_ID_VARNAME, 'ReactSRRootElement');
		return `<div id="ReactSRRootElement">${str}</div>`;
	}
}
