import React from 'react';
import { BrowserRouter as Router, Switch } from 'react-router-dom';
import PrivateRoute from './shared/PrivateRoute';
import PublicRoute from './shared/PublicRoute';

import { connect } from 'react-redux';
import { currentUser } from '../actions/auth';
import { setConfig } from '../actions/config';
import { getSite } from '../actions/site';

import devcms from '@devcms/sdk';

import Admin from './admin/Admin';
import Login from './public/Login';
import Loader from './shared/Loader';
import Notices from './shared/Notices';

class App extends React.Component {
  state = {
    loaded: false
  };

  constructor(props) {
    super(props);

    props.setConfig({
      basename: props.basename,
      base_api_url: props.base_api_url
    });
  }

  componentDidMount() {
    devcms.config.init({ base_api_url: this.props.base_api_url });

    this.props.getSite()
      .then(() => this.props.currentUser())
      .then(() => this.setState({ loaded: true }))
  }

  render() {
    if (!this.state.loaded) {
      return <Loader/>;
    }

    return (
      <Router basename={this.props.basename}>
        <Switch>
          <PublicRoute path="/login" exact component={Login} />
          <PrivateRoute component={Admin} />
        </Switch>
        <Notices />
      </Router>
    );
  }
}

export default connect(
  (state) => ({
    auth: state.auth,
    site: state.site,
    config: state.config,
  }),
  { currentUser, setConfig, getSite },
)(App)
