import React from 'react';
import { Router, Route } from 'react-router';
import { createHistory } from 'history';

import Containers from 'staff-legacy/containers';
import store from 'staff-legacy/config/store';

const history = createHistory();

function isLoggedin() {
  const { auth } = store.getState();

  return !!auth.token;
}

function redirectToRoot(routerState, replace) {
  if (isLoggedin()) {
    replace(null, `/`);
  }
}

function redirectToLogin(routerState, replace) {
  if (!isLoggedin()) {
    replace(null, `/login`);
  }
}

export default () => (
  <Router history={history}>
    <Route path="/login" component={Containers.Users.Login} onEnter={redirectToRoot} />
    <Route path="/" component={Containers.Root} onEnter={redirectToLogin}>
      <Route path="/banners" component={Containers.Banners.List} />
      <Route path="/exports" component={Containers.Exports.List} />
    </Route>
  </Router>
);

export { history };
