import React, { createContext, useContext, useEffect, useState } from "react";
const initialState = {
  allTrainDiagram: undefined,
  setAllTrainDiagram: () => {},
};

const AllTrainDiagramContext = createContext(initialState);

export const useAllTrainDiagram = () => useContext(AllTrainDiagramContext);

export const AllTrainDiagramProvider = ({ children }) => {
  const [allTrainDiagram, setAllTrainDiagram] = useState();
  const [keyList, setKeyList] = useState(); // 第二要素
  useEffect(
    () => allTrainDiagram && setKeyList(Object.keys(allTrainDiagram)),
    [allTrainDiagram]
  );
  const customData = {};
  useEffect(() => {
    fetch(
      "https://n8n.haruk.in/webhook/CrowdTh%E2%82%AC71m3Ra7!ngLead%E2%82%ACr$"
    )
      .then((res) => res.json())
      .then((res) => res.data)
      .then((res) => {
        const data = {};
        res.forEach((d) => {
          const keys = Object.keys(d);
          data[keys] = d[keys];
        });
        return data;
      })
      .then((res) => {
        Object.assign(res, customData);
        setAllTrainDiagram(res);
      })
      .catch((d) => {
        alert("allTrainDiagram取得エラー/再取得します");
        alert(d);
        fetch(
          "https://script.google.com/macros/s/AKfycbx_s7RB-xTy-iAslFJg7LfplLV09-hjDXEjdi9kCP_JT45wq17Af_IPOKIOqIfaNDg/exec"
        )
          .then((res) => res.json())
          .then((res) => {
            const data = {};
            res.forEach((d) => {
              const keys = Object.keys(d);
              data[keys] = d[keys];
            });
            return data;
          })
          .then((res) => {
            Object.assign(res, customData);
            setAllTrainDiagram(res);
          });
      });
  }, []);

  return (
    <AllTrainDiagramContext.Provider
      value={{ allTrainDiagram, setAllTrainDiagram,keyList }}
    >
      {children}
    </AllTrainDiagramContext.Provider>
  );
};
