import {GlobalVariable} from "@gongt/ts-stl-library/pattern/global-page-data";
import * as PropTypes from "prop-types";
import * as React from "react";
import {WrapComponent} from "./render";

export interface PropsType {
	global: GlobalVariable;
}

export interface GlobalContextContent {
	global: GlobalVariable;
}

export interface GlobalContext {
	context: GlobalContextContent;
}

export function WithGlobalContext<T extends React.ComponentClass<any>>(component: T): T {
	if (!component.contextTypes) {
		component.contextTypes = {};
	}
	if (!component.contextTypes.global) {
		component.contextTypes.global = PropTypes.object;
	}
	return component;
}

@WithGlobalContext
export class ReactEmptyWrapper extends React.Component<WrapComponent, {}> {
	state: {subProps: any} = {subProps: null};
	
	static propTypes = {
		Component: PropTypes.instanceOf(React.Component).isRequired,
		componentName: PropTypes.string,
		props: PropTypes.func,
	};
	
	constructor(props, context) {
		super(props, context);
		this.state.subProps = this.props.props(this.context.global);
	}
	
	componentWillReceiveProps(nextProps, nextContext) {
		this.setState({
			subProps: this.props.props(this.context.global),
		});
	}
	
	render() {
		const Cm = this.props.Component;
		if (!Cm) {
			return <div>
				<h1 style={{color: 'red'}}>
					ReactEmptyWrapper: Invalid Child Component: {this.props.componentName}.
				</h1>
				{React.Children.only(this.props.children)}
			</div>;
		}
		console.log('ReactEmptyWrapper render(): ', Cm.displayName || Cm.name);
		return <Cm {...this.state.subProps}>
			{React.Children.only(this.props.children)}
		</Cm>;
	}
}

export class GlobalContextProvider extends React.Component<PropsType, {}> {
	static childContextTypes: React.ValidationMap<any> = {
		global: PropTypes.object,
	};
	
	getChildContext(): GlobalContextContent {
		return {
			global: this.props.global,
		};
	}
	
	render() {
		return React.Children.only(this.props.children);
	}
}
