`use strict`
import { render } from 'inferno'
import { Provider } from 'inferno-redux';
import { applyMiddleware, createStore, combineReducers } from 'redux';

import { blogReducer, langReducer, themeReducer } from './reducers';
import { fetchLang } from './actions'

import Main from './main.jsx'

export const init_app = () => {
	const logger = process.env.DEBUG ? store => next => action => {
			console.group(action.type)
			console.info('dispatching', action)
			let result = next(action)
			console.log('next state', store.getState())
			console.groupEnd()
			return result
		} : null

	const thunk = store => next => action =>
		typeof action === 'function'
			? action(store.dispatch, store.getState)
			: next(action)

	const persistedState = {
		theme: localStorage.getItem('theme') || themeReducer(undefined, {type: null}),
		lang: localStorage.getItem('lang') ?
			{...langReducer(undefined, {type: null}), lang: localStorage.getItem('lang')} :
			langReducer(undefined, {type: null})
	}
	//const initState = persistedState ? JSON.parse(persistedState) : {}

	const reducers = combineReducers({
		theme: themeReducer,
		lang: langReducer,
		blog: blogReducer
	})

	const store = createStore(
		reducers,
		persistedState,
		process.env.DEBUG ? applyMiddleware(thunk, logger) : applyMiddleware(thunk))

	let savedState = {
		theme: store.getState().theme,
		lang: store.getState().lang.lang
	}
	store.subscribe(() => {
		const state = store.getState()
		if(savedState.theme !== state.theme)
		{
			savedState.theme = state.theme
			localStorage.setItem('theme', state.theme)
		}
		if(savedState.lang !== state.lang.lang)
		{
			savedState.lang = state.lang.lang
			localStorage.setItem('lang', state.lang.lang)
		}
	})

	return store
}

const store = init_app()

store.dispatch(fetchLang(store.getState().lang.lang)).then(() => {
	render(
		<Provider store={store}>
			<Main />
		</Provider>,
		document.getElementById("root"))
})