import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import createAppStore from './redux/store/createAppStore';
import {getIPCRenderer} from './utils';
import packageJson from '../package.json';
import {Provider} from 'react-redux';
import {setActiveRelease} from './redux/actions/release_version_actions';
import {setProviderState} from './redux/actions/mount_actions';
import * as serviceWorker from './serviceWorker';
import 'react-checkbox-tree/lib/react-checkbox-tree.css';

const Constants = require('./constants');

const ipcRenderer = getIPCRenderer();
let store;

if (ipcRenderer) {
  ipcRenderer.once(Constants.IPC_Get_Platform_Reply, (event, platformInfo) => {
    if (platformInfo.Platform === 'linux') {
      const root = document.documentElement;
      root.style.setProperty('--default_font_size', '15.3px');
    }

    ipcRenderer.once(Constants.IPC_Get_State_Reply, (event, result) => {
      if (result.data) {
        store = createAppStore(platformInfo, packageJson.version, result.data);
        store.dispatch(setActiveRelease(result.data.Release, result.data.Version));
        const providerList = [
          ...Constants.PROVIDER_LIST,
          ...store.getState().mounts.RemoteMounts,
        ];
        for (const provider of providerList) {
          let state = result.data[provider] || store.getState().mounts.ProviderState[provider];
          if (state.AutoMount === undefined) {
            state['AutoMount'] = false;
          }
          if (state.AutoRestart === undefined) {
            state['AutoRestart'] = false;
          }
          store.dispatch(setProviderState(provider, state));
        }
      } else {
        store = createAppStore(platformInfo, packageJson.version, {});
      }

      ReactDOM.render((
        <Provider store={store}>
          <App/>
        </Provider>
      ), document.getElementById('root'));
      serviceWorker.unregister();
    });
    ipcRenderer.send(Constants.IPC_Get_State);
  });
  ipcRenderer.send(Constants.IPC_Get_Platform);
}

