import React from 'react'
// import hoistStatics from 'hoist-non-react-statics'

/*

A function which binds your component and its associated action functions to a store object so that 
the component and the actions can be exported separately.

All instances of the same component are common subscribers and are re-rendering is done using the
'reRender' property passed along with the store to your actions

You get the actions and state injected in your component as storifyActions and storifyState respectively

*/

var store = {}
var i = 0

export default function storify(Observer, actions, initialState) {
	
	var componentName = Observer.name || Observer.displayName
	
	//unique key for each component
	var storeKey = componentName + String(i++)
	store[storeKey]=initialState
	store[storeKey].subscribers = []
	var reRender = () => {
		store[storeKey].subscribers.forEach(subscriber=>subscriber())
	}

	var boundActions = actions(store[storeKey],reRender)

	class Wrap extends React.Component {
		componentDidMount = () => {
			store[storeKey].subscribers.push(()=>{this.setState({})})
		}

		render = () => <Observer {...this.props} storifyActions={boundActions} storifyState={store[storeKey]}/>
	}

	// hoistStatics(Wrap, Observer);
	Wrap.displayName = componentName
	return { Wrap, ...boundActions }
}