import React, { useEffect } from 'react';

import { Route } from 'react-router-dom';
import { isEmpty, map } from 'lodash';
import { observer } from 'mobx-react';

import AuthenticatedRoute from './AuthenticatedRoute';

import * as allRoutes from './routes';
import useStore from '../data/store';

const AppRoutes = () => {
  const { userStore, appStore } = useStore();

  useEffect(() => {
    userStore.fetchCurrentUser().then(() => {
      console.log('Fetched user');
      if (userStore.userSignedIn) appStore.startListeningToAccountChannel();
    });
  }, []);

  if (userStore.fetchingCurrentUser) return null;

  return (
    <>
      {map(allRoutes.normalRoutes, (r, i) => (
        <Route key={i} exact path={r.route} component={r.component} />
      ))}
      {map(allRoutes.protectedRoutes, (r, i) => (
        <AuthenticatedRoute key={i} path={r.route} component={r.component} />
      ))}
    </>
  );
};

export default observer(AppRoutes);
