/*
 * Copyright (c) 2020 ETSI.  All rights reserved.
 */

// Import CSS
import 'material-design-icons/iconfont/material-icons.css';
import 'leaflet/dist/leaflet.css';
import 'mapbox-gl/dist/mapbox-gl.css';
import 'ionicons/scss/ionicons.scss';
import '../css/app-controller.scss';

// Import module dependencies
import 'material-design-icons';
import React from 'react';
import ReactDOM from 'react-dom';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import appReducer from './state/app-reducer';

import { saveState, loadState } from './util/persist';


// UI Components
import AppContainer from './containers/app-container';

// Initialize variables and listeners when document ready

// Get state from local storage
// Set state to 'undefined' to use default values
var loadedState = loadState();

// Uncomment if logger middleware is needed
// var logger = store => () => action => {
//   console.log(`logger - action: ${action.type}. payload: `, action.payload);
//   console.log('state: ', store.getState());
// };

// Create state store
const appStore = createStore(
  appReducer,
  loadedState ? loadedState : undefined,
  applyMiddleware(
    thunk
  )
);
window.appStore = appStore;

appStore.subscribe(() => {
  var curState = appStore.getState();

  // Filter state to be persisted
  // NOTE: do not modify current state!
  var filteredState = {
    monitor: curState.monitor,
    settings: curState.settings,
    ui: curState.ui
  };

  saveState(filteredState);
});

// Monitor Page
let appContainerPlaceholder = document.getElementById('app-container');
ReactDOM.render(
  <Provider store={appStore}>
    <AppContainer />
  </Provider>,
  appContainerPlaceholder
);
