import React, { createContext, useContext, useState, useEffect } from "react";

import { ASCore } from "../storageControl";

import { getStationList2 } from "../lib/getStationList2";
import { injectJavascriptData } from "../lib/webViewInjectjavascript";

const initialState = {
  selectedLine: undefined,
  setSelectedLine: () => {},
  mapsStationData: undefined,
  setMapsStationData: () => {},
  injectJavaScript: "",
  setInjectJavaScript: () => {},
  iconSetting: undefined,
  setIconSetting: () => {},
  mapSwitch: undefined,
  setMapSwitch: () => {},
  stationMenu: undefined,
  setStationMenu: () => {},
  LoadError: false,
  setLoadError: () => {},
  trainInfo: {
    trainNum: undefined,
    limited: undefined,
    trainData: undefined,
  },
  setTrainInfo: () => {},
  trainMenu: "true",
  setTrainMenu: () => {},
  injectJavascript: "",
};

const TrainMenuContext = createContext(initialState);

export const useTrainMenu = () => {
  return useContext(TrainMenuContext);
};

export const TrainMenuProvider = ({ children }) => {
  const [selectedLine, setSelectedLine] = useState(undefined);
  const [mapsStationData, setMapsStationData] = useState(undefined);
  const [injectJavaScript, setInjectJavaScript] = useState();

  useEffect(() => {
    getStationList2().then(setMapsStationData);
  }, []);

  //画面表示関連
  const [iconSetting, setIconSetting] = useState(undefined);
  const [mapSwitch, setMapSwitch] = useState(undefined);
  const [stationMenu, setStationMenu] = useState(undefined);
  const [LoadError, setLoadError] = useState(false);

  //列車情報表示関連
  const [trainInfo, setTrainInfo] = useState({
    trainNum: undefined,
    limited: undefined,
    trainData: undefined,
  });

  //駅情報画面用
  const [trainMenu, setTrainMenu] = useState("true");

  //地図表示テキスト
  const injectJavascript = injectJavascriptData(
    mapSwitch,
    iconSetting,
    stationMenu,
    trainMenu
  );

  useEffect(() => {
    //列車アイコンスイッチ
    ASCore({ k: "iconSwitch", s: setIconSetting, d: "true", u: true });
    //地図スイッチ
    //6.0.0以降true
    ASCore({ k: "mapSwitch", s: setMapSwitch, d: "false", u: true });
    //駅メニュースイッチ
    ASCore({ k: "stationSwitch", s: setStationMenu, d: "true", u: true });
    //列車メニュースイッチ
    ASCore({ k: "trainSwitch", s: setTrainMenu, d: "true", u: true });
  }, []);

  return (
    <TrainMenuContext.Provider
      value={{
        selectedLine,
        setSelectedLine,
        mapsStationData,
        setMapsStationData,
        injectJavaScript,
        setInjectJavaScript,
        iconSetting,
        setIconSetting,
        mapSwitch,
        setMapSwitch,
        stationMenu,
        setStationMenu,
        LoadError,
        setLoadError,
        trainInfo,
        setTrainInfo,
        trainMenu,
        setTrainMenu,
        injectJavascript,
      }}
    >
      {children}
    </TrainMenuContext.Provider>
  );
};
