import React, {useContext, useState} from "react";

import api from "../../services/vehiclesAPI";
import { LocalDateTimeString } from "../../utils/dates";
import {useInterval} from "usehooks-ts";

const CANSignalContext = React.createContext();

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

const transformSignals = (signals) =>
  signals
    .map((signal) => {
      const { timestamp, value, name } = signal;

      return {
        timestamp: LocalDateTimeString(timestamp),
        signal: name,
        value: value,
      };
    })
    .flat();

export const CANSignalProvider = ({ token, children }) => {
  const [vin, setVIN] = useState(null);
  const [signals, setSignals] = useState([]);
  const [delay, setDelay] = useState(500);

  useInterval(
    () => {
      getCANSignals()
    }, vin?delay:null
  )

  const getCANSignals = async () => {
    try {
      if (!vin) return;

      const result = await api.getCANSignals(vin, token);
      if (result.error)
        throw new Error(`Get CAN signals error. ${result.message}`);

      const items = transformSignals(result.data);

      if (items.length > 0) {
        setDelay(500);
        setSignals(items);
      } else {
        setDelay(1000);
        setSignals([BlankSignal("No signals")]);
      }
    } catch (e) {
      setSignals([BlankSignal(e.message)]);
    }
  };

  return (
    <CANSignalContext.Provider
      value={{
        signals,
        setVIN,
      }}
    >
      {children}
    </CANSignalContext.Provider>
  );
};

export const useCANSignalContext = () => useContext(CANSignalContext);
