Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
10 kB
2
Indexable
Never
import React, { useState, createContext, useEffect } from "react";
import { Grid, alpha, styled, InputBase, Skeleton } from "@mui/material";
import VehicleCard from "../../components/ui/card";
import CustomAppBar from "../../components/ui/appbar";
import Map from "./maps";
import SearchIcon from "@mui/icons-material/Search";
import { GET_ALL_DEVICES } from "../../config/graphql/queries.js";
import { useQuery } from "@apollo/client";

const Search = styled(Grid)(({ theme }) => ({
  position: "relative",
  border: `1px solid ${theme.palette.grey3.main}`,
  borderRadius: "8px",
  backgroundColor:
    theme.palette.mode === "light" ? theme.palette.grey5.main : "#222222",
  "&:hover": {
    backgroundColor: alpha(theme.palette.common.black, 0.25),
  },
  width: "100%",
}));

const SearchIconWrapper = styled(Grid)(({ theme }) => ({
  padding: theme.spacing(0, 2),
  height: "100%",
  position: "absolute",
  pointerEvents: "none",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
}));

const StyledInputBase = styled(InputBase)(({ theme }) => ({
  color: "inherit",
  width: "100%",
  "& .MuiInputBase-input": {
    padding: theme.spacing(1, 1, 1, 0),
    paddingLeft: `calc(1em + ${theme.spacing(4)})`,
    transition: theme.transitions.create("width"),
    width: "100%",
  },
}));

export const MapStatusBarCountContext = createContext(null);

const isLoading = true;
const Dashboard = () => {
  const [allVehicles, setAllVehicles] = useState([]);
  const [runningVehicles, setRunningVehicles] = useState([]);
  const [idleVehicles, setIdleVehicles] = useState([]);
  const [haltVehicles, setHaltVehicles] = useState([]);
  const [nogpsVehicles, setNogpsVehicles] = useState([]);
  const [offlineVehicles, setOfflineVehicles] = useState([]);
  const [disconVehicles, setDisconVehicles] = useState([]);
  const [nodataVehicles, setNodataVehicles] = useState([]);

  const { data, startPolling, stopPolling } = useQuery(GET_ALL_DEVICES);

  useEffect(() => {
    startPolling(10000);
    return () => {
      stopPolling();
    };
  }, [startPolling, stopPolling]);

  useEffect(() => {
    let allVehcilesList = [],
      runningVehiclesList = [],
      idleVehiclesList = [],
      haltVehiclesList = [],
      nogpsVehiclesList = [],
      offlineVehiclesList = [],
      disconVehiclesList = [],
      nodataVehiclesList = [];
    if (data) {
      console.log(data.devices.length);
      for (let i in data.devices) {
        if (data.devices[i].isNoData) nodataVehiclesList.push(data.devices[i]);
        else if (
          data.devices[i].isOffline &&
          data.devices[i].isPrimaryBattery === false
        )
          disconVehiclesList.push(data.devices[i]);
        else if (data.devices[i].isOffline)
          offlineVehiclesList.push(data.devices[i]);
        else if (data.devices[i].isNoGps)
          nogpsVehiclesList.push(data.devices[i]);
        else if (data.devices[i].haltStatus)
          haltVehiclesList.push(data.devices[i]);
        else if (data.devices[i].idlingStatus)
          idleVehiclesList.push(data.devices[i]);
        else runningVehiclesList.push(data.devices[i]);
      }
      allVehcilesList = [
        ...runningVehiclesList,
        ...idleVehiclesList,
        ...haltVehiclesList,
        ...nogpsVehiclesList,
        ...offlineVehiclesList,
        ...disconVehiclesList,
        ...nodataVehiclesList,
      ];

      setAllVehicles(allVehcilesList);
      setRunningVehicles(runningVehiclesList);
      setIdleVehicles(idleVehiclesList);
      setHaltVehicles(haltVehiclesList);
      setNodataVehicles(nodataVehiclesList);
      setNogpsVehicles(nogpsVehiclesList);
      setDisconVehicles(disconVehiclesList);
      setOfflineVehicles(offlineVehiclesList);
    }
  }, [data]);

  const [searchValue, setSearchValue] = useState("");

  const handleSearchBarChange = (event) => {
    setSearchValue(event.target.value);
    setCardList(
      cardList.filter((card) =>
        card.vehicleNumber
          .toLowerCase()
          .includes(event.target.value.toLowerCase())
      )
    );
  };

  const [cardList, setCardList] = useState([]);
  const [godsViewToggle, setGodsViewToggle] = useState(false);
  const [isBackdropOn, setBackdropOn] = useState(false);
  const handleGodsViewToggle = (event) => {
    setGodsViewToggle(event.target.checked);
  };

  const [trackOption, setTrackOption] = useState("All Vehicles");

  const handleTrackOption = (event, newOption) => {
    if (newOption !== null) {
      setTrackOption(newOption);
    }
  };

  const communicateBackdropState = (isOn) => {
    setBackdropOn(isOn);
  };

  useEffect(() => {
    if (trackOption === "All Vehicles") setCardList(allVehicles);
    else if (trackOption === "Running") setCardList(runningVehicles);
    else if (trackOption === "Idle") setCardList(idleVehicles);
    else if (trackOption === "Halted") setCardList(haltVehicles);
    else if (trackOption === "No GPS") setCardList(nogpsVehicles);
    else if (trackOption === "Offline") setCardList(offlineVehicles);
    else if (trackOption === "Disconnected") setCardList(disconVehicles);
    else if (trackOption === "No Data") setCardList(nodataVehicles);
  }, [trackOption, allVehicles]);

  const [selectedCard, setSelectedCard] = useState("");
  const handleSelectedCard = ({ e = null, vehicleNumber }) => {
    if (e !== null) e.stopPropagation();
    setSelectedCard(vehicleNumber);
    if (vehicleNumber === "") setMapViewMode("Overview");
    else setMapViewMode("Live");
  };

  const [mapViewMode, setMapViewMode] = useState("Overview");

  return (
    <>
      <CustomAppBar
        godsViewToggle={godsViewToggle}
        handleGodsViewToggle={handleGodsViewToggle}
        communicateBackdropState={communicateBackdropState}
      />
      {isBackdropOn && (
        <div
          style={{
            background: "#000000 0% 0% no-repeat padding-box",
            position: "absolute",
            zIndex: "200",
            opacity: "0.72",
            top: "window.pageYOffset || document.documentElement.scrollTop",
            left: "window.pageXOffset || document.documentElement.scrollLeft",
            width: "100%",
            height: "100%",
          }}
        ></div>
      )}
      <Grid
        container
        justifyContent="center"
        alignItems="flex-start"
        sx={{ padding: (theme) => theme.spacing(2) }}
      >
        {!godsViewToggle && (
          <Grid
            item
            xs={12}
            sm={6}
            md={5}
            lg={4}
            xl={3}
            sx={{ paddingRight: (theme) => theme.spacing(1) }}
          >
            <Search item>
              <SearchIconWrapper>
                <SearchIcon />
              </SearchIconWrapper>
              <StyledInputBase
                placeholder="Search for Vehicles/Groups"
                inputProps={{ "aria-label": "search" }}
                onChange={handleSearchBarChange}
                value={searchValue}
              />
            </Search>
            <Grid
              container
              direction="row"
              justifyContent="center"
              alignItems="center"
              sx={{
                maxHeight: "78vh",
                overflow: "auto",
                marginTop: (theme) => theme.spacing(2),
                "& > .MuiGrid-item": {
                  marginBottom: (theme) => theme.spacing(2),
                },
              }}
            >
              {cardList.map((card) => (
                <Grid item key={card.uniqueId} xs={12}>
                  {isLoading ? (
                    <VehicleCard
                      key={card.uniqueId}
                      status={
                        card.isNoData
                          ? "No Data"
                          : card.isOffline && card.isPrimaryBattery === false
                          ? "Disconnected"
                          : card.isOffline
                          ? "Offline"
                          : card.isNoGps
                          ? "No GPS"
                          : card.haltStatus
                          ? "Halted"
                          : card.idlingStatus
                          ? "Idle"
                          : "Running"
                      }
                      vehicleNumber={card.vehicleNumber}
                      since={card.since}
                      currentFuel={card.currentFuel}
                      tankCapacity={card.tankCapacity}
                      speed={card.speed}
                      odometer={card.odometer}
                      address={card.address}
                      lastUpdated={card.timestamp}
                      selectedCard={selectedCard}
                      handleSelectedCard={handleSelectedCard}
                    />
                  ) : (
                    <Skeleton
                      variant="rectangular"
                      animation
                      width={426}
                      height={226}
                    />
                  )}
                </Grid>
              ))}
            </Grid>
          </Grid>
        )}
        <Grid item xs={12} sm md lg xl>
          <MapStatusBarCountContext.Provider
            value={{
              countAllVehicles: allVehicles.length,
              countRunningVehicles: runningVehicles.length,
              countIdleVehicles: idleVehicles.length,
              countHaltVehicles: haltVehicles.length,
              countNoGPSVehicles: nogpsVehicles.length,
              countOfflineVehicles: offlineVehicles.length,
              countDisconnectedVehicles: disconVehicles.length,
              countNoDataVehicles: nodataVehicles.length,
            }}
          >
            <Map
              godsViewToggle={godsViewToggle}
              vehicleData={cardList}
              trackOption={trackOption}
              handleTrackOption={handleTrackOption}
              selectedCard={selectedCard}
              handleSelectedCard={handleSelectedCard}
              mapViewMode={mapViewMode}
              setMapViewMode={setMapViewMode}
            />
          </MapStatusBarCountContext.Provider>
        </Grid>
      </Grid>
    </>
  );
};

export default Dashboard;