import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, browserHistory, IndexRoute} from 'react-router';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware, compose} from 'redux';
import reducers from './reducers';
import routes from './routes';
import thunk from 'redux-thunk';
import {set_i18n} from './actions';
import i18next from 'i18next';

const middleware = [thunk];

const composeEnhancers =
  typeof window === 'object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
      // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
    }) : compose;

const enhancer = composeEnhancers(
  applyMiddleware(...middleware),
  // other store enhancers if any
);

let {NODE_ENV} = process.env;

const store = createStore(reducers, NODE_ENV && NODE_ENV == 'production' ? applyMiddleware(...middleware) : enhancer  );

// store.subscribe(() => {
//     console.log(store.getState().dialog);
// });

class PageRoot extends React.Component {

	componentDidMount(){
		let lang = navigator
            .language
            .substring(0, 2);
        fetch(`/locales/${lang}.json`).then(response => {
            if (response.status == 200) 
                return response.json();
            return {}
        }).then(json => {
            let lang = Object.keys(json)[0] || '';
            i18next.init({
                lng: lang,
                resources: json
            }, () => {
                store.dispatch(set_i18n(i18next));
            })
        })
	}

	render() {
		return (
			<Provider store={store}>
				<Router history={browserHistory} routes={routes}/>
			</Provider>
		)
	}
}

ReactDOM.render(
    <PageRoot />,
    document.getElementById('app')
);