import 'react-app-polyfill/stable';
import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
import 'react-bootstrap-table2-paginator/dist/react-bootstrap-table2-paginator.min.css';
import 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit.min.css';
import 'react-bootstrap-typeahead/css/Typeahead.css';
import 'react-datetime/css/react-datetime.css'; // dependency of `react-combo-search`
import 'react-combo-select/style.css'; // dependency of `react-combo-search`
import 'react-combo-search/css/style.css';
import 'react-day-picker/lib/style.css';
import 'react-vis/dist/style.css';
import './index.css';

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { CacheProvider } from 'rest-hooks';
import App from './App';
import { unregister } from './registerServiceWorker';
import { persistor, store } from './store';
import ScrollToTop from './components/ScrollToTop';
import { BrowserRouter } from 'react-router-dom';
import keycloak from './config/sso/keycloak';
import { checkExpirationTime, matchAuthStateToSSO } from './helpers/auth';
import { doLogOut } from './actions/login';

function prepareAuth() {
  // If a persisted ICAT session was just restored, make sure it's not expired (or about to expire)
  checkExpirationTime();

  if (keycloak) {
    // When keycloak detects a log out or fails to refresh the access token, log out from ICAT
    keycloak.onAuthLogout = () => {
      if (store.getState().user.isSSO) {
        store.dispatch(doLogOut());
      }
    };

    // Make sure ICAT authentication state is consistent with SSO (i.e. log in/out as needed)
    matchAuthStateToSSO();
  }
}

function renderApp() {
  render(
    <CacheProvider>
      <Provider store={store}>
        <PersistGate onBeforeLift={prepareAuth} persistor={persistor}>
          <BrowserRouter>
            <ScrollToTop />
            <App />
          </BrowserRouter>
        </PersistGate>
      </Provider>
    </CacheProvider>,
    document.getElementById('root')
  );
}

if (keycloak) {
  // Initialise SSO before rendering the app
  keycloak
    .init({
      onLoad: 'check-sso',
      silentCheckSsoRedirectUri: `${window.location.origin}/silent-check-sso.html`,
    })
    .then(renderApp);
} else {
  renderApp();
}

// Remove any installed service worker
unregister();
