/* eslint-disable global-require */

import React from 'react';
import { render } from 'react-dom';
import BrowserRouter from 'react-router-dom/BrowserRouter';
import asyncBootstrapper from 'react-async-bootstrapper';
import { AsyncComponentProvider } from 'react-async-component';
import configureStore from '../shared/redux/configureStore';
import { JobProvider } from 'react-jobs';
import { Provider } from 'react-redux';
import { loadUser, userNotLoggedIn } from '../shared/actions/userActions';

import './polyfills';

import ReactHotLoader from './components/ReactHotLoader';
import App from '../shared/components';

// Get the DOM Element that will host our React application.
const container = document.querySelector('#app');

// Does the userReducers's browser support the HTML5 history API?
// If the userReducers's browser doesn't support the HTML5 history API then we
// will force full page refreshes on each page change.
const supportsHistory = 'pushState' in window.history;

// Get any rehydrateState for the async components.
// eslint-disable-next-line no-underscore-dangle
const asyncComponentsRehydrateState = window.__ASYNC_COMPONENTS_REHYDRATE_STATE__;

const store = configureStore(
  // Server side rendering would have mounted our state on this global.
  window.__APP_STATE__, // eslint-disable-line no-underscore-dangle
);

// Get any "rehydrate" state sent back by the server
// eslint-disable-next-line no-underscore-dangle
const rehydrateState = window.__JOBS_STATE__;

var BrowserDetect = {
  init: function () {
      this.browser = this.searchString(this.dataBrowser) || "Other";
      this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
  },
  searchString: function (data) {
      for (var i = 0; i < data.length; i++) {
          var dataString = data[i].string;
          this.versionSearchString = data[i].subString;

          if (dataString.indexOf(data[i].subString) !== -1) {
              return data[i].identity;
          }
      }
  },
  searchVersion: function (dataString) {
      var index = dataString.indexOf(this.versionSearchString);
      if (index === -1) {
          return;
      }

      var rv = dataString.indexOf("rv:");
      if (this.versionSearchString === "Trident" && rv !== -1) {
          return parseFloat(dataString.substring(rv + 3));
      } else {
          return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
      }
  },

  dataBrowser: [
      {string: navigator.userAgent, subString: "Edge", identity: "MS Edge"},
      {string: navigator.userAgent, subString: "MSIE", identity: "Explorer"},
      {string: navigator.userAgent, subString: "Trident", identity: "Explorer"},
      {string: navigator.userAgent, subString: "Firefox", identity: "Firefox"},
      {string: navigator.userAgent, subString: "Opera", identity: "Opera"},  
      {string: navigator.userAgent, subString: "OPR", identity: "Opera"},  

      {string: navigator.userAgent, subString: "Chrome", identity: "Chrome"}, 
      {string: navigator.userAgent, subString: "Safari", identity: "Safari"}       
  ]
};

BrowserDetect.init();
let isUnsupportedBrower = false;

// if(BrowserDetect.browser === "Explorer" || BrowserDetect.browser === "MS Edge") {
//   isUnsupportedBrower = true;
// }
/**
 * Renders the given React Application component.
 */
function renderApp(TheApp) {
  // Firstly, define our full application component, wrapping the given
  // component app with a browser based version of react router.
  let app;
  if (isUnsupportedBrower) {
    app = <div>
      Dear client,<br />
      <br />
      Unfortunately our client portal is not yet supported by the browsers:<br />
      Edge and Internet Explorer.<br />
      <br />
      Please use the browsers <a href="https://www.google.com/chrome/" target="_blank">Chrome</a>, <a href="https://www.mozilla.org/en-US/firefox/new/" target="_blank">Firefox</a>, <a href="https://support.apple.com/downloads/safari" target="_blank">Safari</a> or <a href="http://www.opera.com/download" target="_blank">Opera</a> to enter our online client portal. Our apologies for the inconvenience caused.<br />
      <br />
      We hope to assist you soon. For questions, please contact us via info@ttmtax.nl.<br />
      <br />
      Best regards,<br />
      <br />
      Team TTMTAX
    </div>
  } else {
    app = (
      <ReactHotLoader>
        <AsyncComponentProvider rehydrateState={asyncComponentsRehydrateState}>
          <JobProvider rehydrateState={rehydrateState}>
            <BrowserRouter forceRefresh={!supportsHistory}>
              <Provider store={store}>
                <TheApp />
              </Provider>
            </BrowserRouter>
          </JobProvider>
        </AsyncComponentProvider>
      </ReactHotLoader>
    );
  }

  // We use the react-async-component in order to support code splitting of
  // our bundle output. It's important to use this helper.
  // @see https://github.com/ctrlplusb/react-async-component
  asyncBootstrapper(app).then(() => render(app, container));
}

const token = localStorage.getItem('token');
if (token !== null) {
  store.dispatch(loadUser(token));
} else {
  store.dispatch(userNotLoggedIn());
}

// Execute the first render of our app.
renderApp(App);

// This registers our service worker for asset caching and offline support.
// Keep this as the last item, just in case the code execution failed (thanks
// to react-boilerplate for that tip.)
require('./registerServiceWorker');

// The following is needed so that we can support hot reloading our application.
if (process.env.BUILD_FLAG_IS_DEV === 'true' && module.hot) {
  // Accept changes to this file for hot reloading.
  module.hot.accept('./index.js');
  // Any changes to our App will cause a hotload re-render.
  module.hot.accept('../shared/components', () => {
    renderApp(require('../shared/components').default);
  });
}
