import React, { useContext, useState } from "react";
import api from "../../services/CANSignalAPI";
import { validateVIN } from "../../utils/validationSupplier";

const CANSignalsExportContext = React.createContext();

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

  const [canSignals, setCanSignals] = useState([]);

  const getCANSignalList = async (token) => {
    try {
      setBusy(true);
      const result = await api.getCanSignalList(token);
      if (result.error) {
        throw new Error(`Get can signal list error. ${result.message}`);
      }
      setCanSignals(result.data ?? []);
      return result;
    } finally {
      setBusy(false);
    }
  };

  const getDynamicColumnCANSignals = async (vin, timestart, timeend, cansignals, selectall, token) => {
    try {
      setBusy(true)
      if (!vin) return;

      validateVIN(vin);
      if (timestart > timeend) throw new Error("Start time cannot be after end time");

      let result
      if (selectall === true) {
        result = await api.getCanSignalsVin(vin, timestart, timeend, [], selectall, token);
      } else {
        result = await api.getCanSignalsVin(vin, timestart, timeend, cansignals, false, token);
      }
      if (result.error || !result.ok)
        throw new Error(`Get CAN signals error. ${result.message}`);

      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 = 'CAN_signals.csv';
        link.click();
      };
      reader.readAsText(blob);
    } catch (e) {
      throw new Error(e)
    }
    finally {
      setBusy(false)
    }
  }

  return (
    <CANSignalsExportContext.Provider
      value={{
        busy,
        canSignals,
        getCANSignalList,
        getDynamicColumnCANSignals
      }}
    >
      {children}
    </CANSignalsExportContext.Provider>
  );
};

export const useCANSignalsExportContext = () => useContext(CANSignalsExportContext);



