import React, { Component } from 'react';
import Routes, { history } from 'cem/config/routes';

import { Provider } from 'react-redux';
import { persistStore } from 'redux-persist';
import { syncReduxAndRouter } from 'redux-simple-router';

import store from 'cem/config/store';
import { CEM } from 'cem/config/api';

export default class extends Component {
  constructor() {
    super();

    this.state = {};
  }

  componentWillMount() {
    persistStore(store, { whitelist: [`auth`] }, () => {
      syncReduxAndRouter(history, store);

      this.setState({ rehydrated: true }, () => {
        const { auth } = store.getState();

        if (auth.token) {
          CEM.setHeader(`Authorization`, `Token ${auth.token}`);
        }
      });
    });
  }

  render() {
    if (!this.state.rehydrated) {
      return null;
    }

    return (
      <Provider store={store}>
        <Routes />
      </Provider>
    );
  }
}
