import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
} from "@material-ui/core";
import React, { useEffect, useState } from "react";
import { logger } from "../../../services/monitoring";
import { LocalDateTimeString } from "../../../utils/dates";

import { useVehicleContext } from "../../Contexts/VehicleContext";

const BlankSignal = (msg) => ({
  timestamp: "",
  signal: msg,
  value: "",
});

const transformSignals = (signals) =>
  signals
    .map((signal) => {
      const { Timestamp, ...Settings } = signal;
      const keys = Object.keys(Settings);

      return keys.map((key) => ({
        timestamp: LocalDateTimeString(Timestamp),
        signal: key,
        value: Settings[key],
      }));
    })
    .flat();

const CANSignals = (props) => {
  const { vin, token } = props;
  const { getCANSignals } = useVehicleContext();
  const [signals, setSignals] = useState([]);
  const delay = 500;
  let timer = 0;

  const stopTimer = async () => {
    if (timer === 0) return;
    clearTimeout(timer);
    timer = 0;
  };

  const startTimer = () => {
    stopTimer();
    timer = setTimeout(() => {
      updateSignals();
    }, delay);
  };

  const updateSignals = async () => {
    try {
      const result = await getCANSignals(vin, token);
      const items = transformSignals(result.data);

      if (items.length > 0) {
        setSignals(items);
      } else {
        setSignals([BlankSignal("No signals")]);
      }

      if (delay > 0) startTimer();
    } catch (e) {
      setSignals([BlankSignal(e.message)]);
      logger.warn(e.stack);
    }
  };

  useEffect(() => {
    startTimer();
    return () => {
      stopTimer();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!signals || signals.length === 0) return <h3>Loading...</h3>;

  return (
    <Table>
      <TableHead>
        <TableRow>
          <TableCell>Timestamp</TableCell>
          <TableCell>Signal</TableCell>
          <TableCell>Value</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {signals.map((signal, i) => (
          <TableRow key={i}>
            <TableCell>{signal.timestamp}</TableCell>
            <TableCell>{signal.signal}</TableCell>
            <TableCell>{signal.value}</TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
};

export default CANSignals;
