From 3e61ded95adc52d3a1c4be483e100ca6e4812e09 Mon Sep 17 00:00:00 2001
From: Karel Hala <khala@redhat.com>
Date: Sun, 18 Sep 2022 20:13:21 +0200
Subject: [PATCH] Add nav to show all API resources and call them

---
 src/components/DataTable.js    |  2 +-
 src/components/Navigation.js   | 36 ++++++++++++++++----
 src/components/PrivateRoute.js | 16 +--------
 src/utils/helpers.js           | 10 ++++++
 src/views/HomePage.js          | 61 +++++++++++++++++++++++++++++-----
 src/views/Profile.js           |  5 ++-
 6 files changed, 97 insertions(+), 33 deletions(-)
 create mode 100644 src/utils/helpers.js

diff --git a/src/components/DataTable.js b/src/components/DataTable.js
index 7a0a549..ec98bd3 100644
--- a/src/components/DataTable.js
+++ b/src/components/DataTable.js
@@ -34,7 +34,7 @@ function createData({ month, year, ...row }) {
 }
 
 const headerTemplate = {
-  year: 'Year',
+  year: 'Rok',
   month: 'Měsíc',
   labels: createNumbers(),
 };
diff --git a/src/components/Navigation.js b/src/components/Navigation.js
index 6327a1f..20b3aa2 100644
--- a/src/components/Navigation.js
+++ b/src/components/Navigation.js
@@ -4,9 +4,12 @@ import ListItem from '@material-ui/core/ListItem';
 import ListItemIcon from '@material-ui/core/ListItemIcon';
 import ListItemText from '@material-ui/core/ListItemText';
 import ShowChartIcon from '@material-ui/icons/ShowChart';
-import DashboardIcon from '@material-ui/icons/Dashboard';
-import { NavLink as RouterNavLink } from 'react-router-dom';
+import WbSunnyIcon from '@material-ui/icons/WbSunny';
+import WavesIcon from '@material-ui/icons/Waves';
+import AcUnitIcon from '@material-ui/icons/AcUnit';
+import { NavLink as RouterNavLink, useLocation } from 'react-router-dom';
 import { makeStyles } from '@material-ui/core/styles';
+import { useType } from '../utils/helpers';
 
 const useStyles = makeStyles((theme) => ({
   link: {
@@ -20,18 +23,37 @@ const useStyles = makeStyles((theme) => ({
 
 const Navigation = () => {
   const styles = useStyles();
+  const { pathname } = useLocation();
+
+  const type = useType();
   return (
     <div>
-      <RouterNavLink to="/home-page" className={({ isActive }) => [clsx(styles.link), isActive ? 'selected' : null].join(' ')}>
-        <ListItem button>
+      <RouterNavLink to="/home-page" className={clsx(styles.link)}>
+        <ListItem button selected={pathname === '/home-page' && !type ? 'selected' : null}>
+          <ListItemIcon>
+            <WbSunnyIcon />
+          </ListItemIcon>
+          <ListItemText primary="Sunshine" />
+        </ListItem>
+      </RouterNavLink>
+      <RouterNavLink to="/home-page?type=air" className={clsx(styles.link)}>
+        <ListItem button selected={pathname === '/home-page' && type === 'air' ? 'selected' : null}>
+          <ListItemIcon>
+            <WavesIcon />
+          </ListItemIcon>
+          <ListItemText primary="Air" />
+        </ListItem>
+      </RouterNavLink>
+      <RouterNavLink to="/home-page?type=temp" className={clsx(styles.link)}>
+        <ListItem button selected={pathname === '/home-page' && type === 'temp' ? 'selected' : null}>
           <ListItemIcon>
-            <DashboardIcon />
+            <AcUnitIcon />
           </ListItemIcon>
-          <ListItemText primary="Dashboard" />
+          <ListItemText primary="Temperture" />
         </ListItem>
       </RouterNavLink>
       <RouterNavLink to="/chart" className={({ isActive }) => [clsx(styles.link), isActive ? 'selected' : null].join(' ')}>
-        <ListItem button>
+        <ListItem button selected={pathname === '/chart'}>
           <ListItemIcon>
             <ShowChartIcon />
           </ListItemIcon>
diff --git a/src/components/PrivateRoute.js b/src/components/PrivateRoute.js
index 5ecf903..4351966 100644
--- a/src/components/PrivateRoute.js
+++ b/src/components/PrivateRoute.js
@@ -5,25 +5,11 @@ import { useAuth0 } from '../react-auth0-spa';
 // import authConfig from '../auth_config.json';
 
 const PrivateRoute = ({ component: Component, ...rest }) => {
-  const { isAuthenticated, loginWithRedirect, user, ...props } = useAuth0();
+  const { isAuthenticated, loginWithRedirect } = useAuth0();
   const location = useLocation();
 
-  console.log(props, 'huuuuhhuuuuhhuuuuh');
-
   useEffect(() => {
     const fn = async () => {
-      console.log(user, 'huuuuh');
-      // const { access_token } = await (
-      //   await fetch(`https://${authConfig.domain}/oauth/token`, {
-      //     method: 'POST',
-      //     headers: { 'content-type': 'application/json' },
-      //     body: JSON.stringify(body),
-      //   })
-      // ).json();
-      // const data = await fetch(`https://${authConfig.domain}/userinfo`, {
-      //   headers: { Authorization: `Bearer ${access_token}`, 'Content-Type': 'application/json' },
-      // });
-      // console.log(await data.json(), 'fuuuuuuuh');
       if (!isAuthenticated) {
         await loginWithRedirect({
           appState: { targetUrl: location.pathname },
diff --git a/src/utils/helpers.js b/src/utils/helpers.js
new file mode 100644
index 0000000..f391f84
--- /dev/null
+++ b/src/utils/helpers.js
@@ -0,0 +1,10 @@
+import { useMemo } from 'react';
+import { useLocation } from 'react-router-dom';
+
+export const useType = () => {
+  const { search } = useLocation();
+  const type = useMemo(() => {
+    return new URLSearchParams(search).get('type');
+  }, [search]);
+  return type;
+};
diff --git a/src/views/HomePage.js b/src/views/HomePage.js
index aa5d2e1..3c838b3 100644
--- a/src/views/HomePage.js
+++ b/src/views/HomePage.js
@@ -6,15 +6,23 @@ import Grid from '@material-ui/core/Grid';
 import Toolbar from '@material-ui/core/Toolbar';
 import Autocomplete from '@material-ui/lab/Autocomplete';
 import { useAuth0 } from '../react-auth0-spa';
+import { useType } from '../utils/helpers';
 
 const queryBuilder = ({ max = 15, skip = 0, filter }) => {
-  return `q={${filter ? `'year': ${filter}` : ''}}&max=${max}&skip=${skip}`;
+  return `q={${filter ? `"year": ${filter}` : ''}}&max=${max}&skip=${skip}`;
+};
+
+const restTypesMapper = {
+  '': ['sunshine', 'snow', 'precipitation'],
+  air: ['wind-speed', 'air-pressure', 'air-moist'],
+  temp: ['temp-avg', 'temp-min', 'temp-max'],
 };
 
 const HomePage = () => {
+  const type = useType();
   const [years, setYears] = useState([]);
   const [data, setData] = useState([]);
-  const { apiSun } = useAuth0();
+  const { apiSun, apiTemp, apiAir } = useAuth0();
   const [{ max, skip, count, filterValue }, setPagination] = useState({
     max: 15,
     skip: 0,
@@ -22,7 +30,29 @@ const HomePage = () => {
     filterValue: '',
   });
   const [initialized, setInitialized] = useState(false);
+  const [{ resource, rest }, setRestApi] = useState({
+    resource: apiSun,
+    rest: 'sunshine',
+  });
 
+  React.useEffect(() => {
+    if (!type) {
+      setRestApi({
+        resource: apiSun,
+        rest: 'sunshine',
+      });
+    } else if (type === 'air') {
+      setRestApi({
+        resource: apiAir,
+        rest: 'wind-speed',
+      });
+    } else if (type === 'temp') {
+      setRestApi({
+        resource: apiTemp,
+        rest: 'temp-avg',
+      });
+    }
+  }, [type]);
   const onFilter = (e, filter) => {
     setPagination((prevPagination) => ({
       ...prevPagination,
@@ -40,21 +70,34 @@ const HomePage = () => {
   useEffect(() => {
     setInitialized(false);
     Promise.all([
-      apiSun.get(`rest/sunshine?${queryBuilder({ max, skip, filter: filterValue })}&totals=true`).then(({ data, totals }) => {
+      resource.get(`rest/${rest}?${queryBuilder({ max, skip, filter: filterValue })}&totals=true`).then(({ data, totals }) => {
         setData(data);
         setPagination((prevPagination) => ({ ...prevPagination, count: totals.total }));
       }),
-      apiSun.get('rest/sunshine?q={}&h={"$fields": {"year": 1}}').then((data) => setYears([...new Set(data.map(({ year }) => `${year}`))])),
+      resource.get(`rest/${rest}?q={}&h={"$fields": {"year": 1}}`).then((data) => setYears([...new Set(data.map(({ year }) => `${year}`))])),
     ]).then(() => setInitialized(true));
-  }, [skip, filterValue]);
+  }, [skip, filterValue, resource, rest]);
+
+  // const addMessage = () => apiSun.updateData('professors.messages', { message: 'Hola' }, 'add');
+  // const replaceMessage = () => apiSun.updateData('professors.messages', { message: 'Hola' }, 'replace');
 
-  const addMessage = () => apiSun.updateData('professors.messages', { message: 'Hola' }, 'add');
-  const replaceMessage = () => apiSun.updateData('professors.messages', { message: 'Hola' }, 'replace');
   return (
     <div>
       <h1>Home page</h1>
-      <button onClick={addMessage}>Add message</button>
-      <button onClick={replaceMessage}>replace message</button>
+      <Grid container spacing={3} justify="space-between">
+        <Grid item>
+          <Autocomplete
+            style={{ minWidth: '300px' }}
+            options={restTypesMapper[type || '']}
+            id="rest-type-picker"
+            value={rest}
+            onChange={(e, filter) => setRestApi(({ resource }) => ({ resource, rest: filter }))}
+            disabled={!initialized}
+            renderInput={(params) => <TextField {...params} label="Select rest type" margin="normal" />}
+          />
+        </Grid>
+      </Grid>
+
       <Toolbar>
         <Grid container spacing={3} justify="space-between">
           <Grid item>
diff --git a/src/views/Profile.js b/src/views/Profile.js
index 02cd1bf..00555b0 100644
--- a/src/views/Profile.js
+++ b/src/views/Profile.js
@@ -5,6 +5,7 @@ import Grid from '@material-ui/core/Grid';
 import './profile.css';
 import Loading from '../components/Loading';
 import { useAuth0 } from '../react-auth0-spa';
+import { Button } from '@material-ui/core';
 import PropTypes from 'prop-types';
 
 const FormTextField = ({ input, meta, ...props }) => (
@@ -50,7 +51,9 @@ const Profile = () => {
                 <Field name="name" component={FormTextField} label="Name" type="text" />
                 <Field name="nickname" component={FormTextField} label="Nickname" type="text" />
                 <Field name="picture" component={FormTextField} label="Picture" type="text" />
-                <button type="submit">Submit</button>
+                <Button type="submit" variant="contained">
+                  Submit
+                </Button>
               </form>
             )}
           </Form>
-- 
GitLab