import React from 'react';
import ReactDOM from 'react-dom';
import * as attachFastClick from 'fastclick';
import { AppContainer } from 'react-hot-loader';
import project from '@project';
import * as services from './services';
import { initStore, refreshStore } from './services/Store';
import App from './containers/App';
import Routes from './routes';
import Stores from './stores';

/**
 * 兼容手机端处理300问题
 */
attachFastClick.attach(document.body);

/**
 * 初始化
 */
const initialState = {};
const store = initStore(initialState, Stores, project, services);
const MOUNT_NODE = document.getElementById('root');
const render = (Component, routes) => {
  if (__DEV__) {
    ReactDOM.render(
      <AppContainer>
        <Component store={store} routes={routes} project={project} history={services.History} />
      </AppContainer>,
      MOUNT_NODE,
    );
  } else {
    ReactDOM.render(
      <Component store={store} routes={routes} project={project} history={services.History} />,
      MOUNT_NODE,
    );
  }
};
if (__DEV__) {
  /**
   * 开发环境处理
   */
  if (module.hot) {
    module.hot.accept(['./containers/App', './routes'], () => {
      Promise.all([import('./containers/App'), import('./routes')]).then(results => {
        const [{ default: component }, { default: routes }] = results;
        ReactDOM.unmountComponentAtNode(MOUNT_NODE);
        render(component, routes);
      });
    });
    module.hot.accept('./stores', () => {
      import('./stores').then(result => {
        refreshStore(store, result.default, project, services);
      });
    });
    module.hot.accept(() => {
      window.location.href = window.location.href;
    });
  }
}

try {
  render(App, Routes);
} catch (err) {
  console.error(err);
}
