import React, { useContext, useState } from "react";
import api from "../../services/DTCTimelineAPI";

const DTCTimelineContext = React.createContext();

export const DTCTimelineProvider = ({ children }) => {
  const [busy, setBusy] = useState(false);

  const [dtcData, setDTCData] = useState([]);
  const [total, setTotal] = useState(0)

  const getDTCData = async (vin, ecu, startDate, endDate, search,token) => {
    try {
      setBusy(true);
      const result = await api.getDTCData(vin, ecu, startDate, endDate, search,token);
      if (result.error) {
        throw new Error(`Get DTC data error. ${result.message}`);
      }
      setDTCData(result.data ?? []);
      if (result.total){
        setTotal(result.total)
      }
      return result;
    } finally {
      setBusy(false);
    }
  };

  return (
    <DTCTimelineContext.Provider
      value={{
        busy,
        total,
        dtcData,
        getDTCData
      }}
    >
      {children}
    </DTCTimelineContext.Provider>
  );
};

export const useDTCTimelineContext = () => useContext(DTCTimelineContext);
