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

const TrainDelayDataContext = createContext(initialState);

export const useTrainDelayData = () => {
  return useContext(TrainDelayDataContext);
};
type props = {
  children: React.ReactNode;
};
export const TrainDelayDataProvider:FC<props> = ({ 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/AKfycbw-0RDLAu8EQAEWA860tk4KVW6VOr3iIU900AcWEfqIP16gtNUG1XO_A3oBfAGiNeCf/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>
  );
};
