import React, { createContext, useContext, useEffect, useState } from "react";
const initialState = {
  getTime: new Date(),
  setGetTime: () => {},
  loadingDelayData: true,
  setLoadingDelayData: () => {},
  delayData: undefined,
  setDelayData: () => {},
};

const TrainDelayDataContext = createContext(initialState);

export const useTrainDelayData = () => {
  return useContext(TrainDelayDataContext);
};

export const TrainDelayDataProvider = ({ children }) => {
  const [delayData, setDelayData] = useState(undefined);
  const [getTime, setGetTime] = useState(new Date());
  const [loadingDelayData, setLoadingDelayData] = useState(true);
  useEffect(() => {
    fetch(
      "https://script.google.com/macros/s/AKfycbyKxch7z7l8e07LXulRHqxjVoIiB13kcgvoToLE-rqlxLmLSKdlmqz0FI1F2EuA7Zfg/exec"
    )
      .then((response) => response.text())
      .then((data) => setDelayData(data !== "" ? data.split("^") : null))
      .then(() => setGetTime(new Date()))
      .finally(() => setLoadingDelayData(false));
  }, [loadingDelayData]);

  return (
    <TrainDelayDataContext.Provider
      value={{
        getTime,
        setGetTime,
        loadingDelayData,
        setLoadingDelayData,
        delayData,
        setDelayData,
      }}
    >
      {children}
    </TrainDelayDataContext.Provider>
  );
};
