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, troubleCode, startDate, endDate, search, token) => {
    try {
      setBusy(true);
      const result = await api.getDTCData(vin, ecu, troubleCode, 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);
    }
  };

  const exportDTCTimeline = async (vin, ecu, troubleCode, startDate, endDate, search, token) => {
    try {
      setBusy(true)
      let result = await api.exportDTCData(vin, ecu, troubleCode, startDate, endDate, search, token);

      const blob = await result.blob();
      const reader = new FileReader();
      reader.onload = () => {
        const csvData = reader.result;
        const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8' });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = 'DTC_timeline.csv';
        link.click();
      };
      reader.readAsText(blob);
    } catch (e) {
      throw new Error(e)
    }
    finally {
      setBusy(false)
    }
  }

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

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