/* globals window, document */
/* eslint react/jsx-filename-extension: "off" */
import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { Router, hashHistory, browserHistory } from 'react-router';
import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux';
import reducers from './reducers';
import Instance from './components/Connection';

const middleware = routerMiddleware(hashHistory);
const store = createStore(
  reducers,
  applyMiddleware(middleware),
);

window.localStorage.setItem('App', '8a266a40-ed2e-4be2-bdfc-459a507bf02e');

// instance.post('/v1/authenticate/portal', {
//   email: 'carlos@brighterdevelopment.com',
//   pass: 'VGVzdDIwMTc=',
// }).then(function (res) { localStorage.setItem('Token', res.data.token) });
const history = syncHistoryWithStore(hashHistory, store);

const isFunction = (functionToCheck) => {
  const getType = {};
  return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
};

const requireAuth = (nextState, replace, next) => {
  if (nextState.location.pathname === '/login' || nextState.location.pathname === '/sign-up' || (nextState.location.pathname.indexOf('/ride') > -1 && nextState.params.ride_uuid !== undefined && nextState.params.user_uuid !== undefined)
    || (!isFunction(replace) && (replace.location.pathname === '/login' || replace.location.pathname === '/sign-up' || (replace.location.pathname.indexOf('/ride') > -1 && replace.params.ride_uuid !== undefined && replace.params.user_uuid !== undefined)))) {
    next();
  }

  const token = Instance.getCookie('token');
  if (!token || token === null || token === undefined || token === '') {
    if (isFunction(replace)) {
      replace('/login');
    } else {
      browserHistory.transitionTo('/login');
    }
  }
  next();
};

function scrollToTop() {
  window.scrollTo(0, 0);
}

const rootRoute = {
  childRoutes: [{
    path: '/',
    onChange: requireAuth,
    onEnter: requireAuth,
    component: require('./containers/App'),
    indexRoute: { onEnter: (nextState, replace) => replace('/app/table/rides') },
    childRoutes: [
      require('./routes/app'),
      require('./routes/404'),
      require('./routes/500'),
      require('./routes/confirmEmail'),
      require('./routes/forgotPassword'),
      require('./routes/lockScreen'),
      require('./routes/login'),
      require('./routes/signUp'),
      require('./routes/selfRegister'),
      require('./routes/fullscreen'),
      require('./routes/ride'),
      require('./routes/ready'),
      {
        path: '*',
        indexRoute: { onEnter: (nextState, replace) => replace('/404') },
      },
    ],
  }],
};

render(
  <Provider store={store}>
    <Router
      onUpdate={scrollToTop}
      history={history}
      routes={rootRoute}
    />
  </Provider>,
  document.getElementById('app-container'),
);
