import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  useRef,
} from "react";
import { HeaderConfig } from "../lib/HeaderConfig";

import useInterval from "../lib/useInterval";
const initialState = {
  webview: {},
  currentTrain: [],
  setCurrentTrain: () => {},
  currentTrainLoading: "loading",
  setCurrentTrainLoading: () => {},
  getCurrentTrain: () => {},
};

const CurrentTrainContext = createContext(initialState);

export const useCurrentTrain = () => {
  return useContext(CurrentTrainContext);
};

export const CurrentTrainProvider = ({ children }) => {
  const [currentTrain, setCurrentTrain] = useState([]); //現在在線中の全列車 { num: 列車番号, delay: 遅延時分(状態), Pos: 位置情報 }
  const [currentTrainLoading, setCurrentTrainLoading] = useState("loading"); // success, error, loading
  const getCurrentTrain = () => {
    fetch("https://n8n.haruk.in/webhook/c501550c-7d1b-4e50-927b-4429fe18931a")
      .then((response) => response.json())
      .then((d) => d.data)
      .then((d) =>
        d.map((x) => ({
          Index: x.Index,
          num: x.TrainNum,
          delay: x.delay,
          Pos: x.Pos,
          PosNum: x.PosNum,
          Direction: x.Direction,
          Type: x.Type,
          Line: x.Line,
        }))
      )
      .then((d) => {
        setCurrentTrain(d);
        setCurrentTrainLoading("success");
      })
      .catch(() => {
        //alert("現在の全在線列車取得エラー/再取得します");
        fetch(
          "https://script.google.com/macros/s/AKfycby9Y2-Bm75J_WkbZimi7iS8v5r9wMa9wtzpdwES9sOGF4i6HIYEJOM60W6gM1gXzt1o/exec",
          HeaderConfig
        )
          .then((response) => response.json())
          .then((d) =>
            d.map((x) => ({ num: x.TrainNum, delay: x.delay, Pos: x.Pos }))
          )
          .then((d) => {
            setCurrentTrain(d);
            setCurrentTrainLoading("success");
          })
          .catch(() => {
            console.log("えらー");
            setCurrentTrainLoading("error");
          });
      });
  };
  const inject = (i) => {
    webview.current?.injectJavaScript(i);
  };

  useEffect(getCurrentTrain, []); //初回だけ現在の全在線列車取得

  useInterval(getCurrentTrain, 15000); //15秒毎に全在線列車取得

  const webview = useRef();
  return (
    <CurrentTrainContext.Provider
      value={{
        webview,
        currentTrain,
        setCurrentTrain,
        currentTrainLoading,
        setCurrentTrainLoading,
        getCurrentTrain,
        inject,
      }}
    >
      {children}
    </CurrentTrainContext.Provider>
  );
};
