import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  FC,
} from "react";
import { lineList, getStationList } from "../lib/getStationList";

type initialStateType = {
  originalStationList: any[][];
  setOriginalStationList: React.Dispatch<React.SetStateAction<any[]>>;
  getStationData: (id: string) => void;
  stationList: any[];
};
const initialState = {
  originalStationList: [[]],
  setOriginalStationList: () => {},
  getStationData: () => {},
  stationList: [],
};

const TopMenuContext = createContext<initialStateType>(initialState);
type Props = {
  children: React.ReactNode;
};
export const useTopMenu = () => {
  return useContext(TopMenuContext);
};

export const TopMenuProvider: FC<Props> = ({ children }) => {
  const [originalStationList, setOriginalStationList] = useState<any[]>([]);
  useEffect(() => {
    getStationList().then(setOriginalStationList);
  }, []);
  const getStationData: (name: string) => void = (name) => {
    const returnArray = [];
    Object.keys(originalStationList).forEach((key) => {
      originalStationList[key].forEach((station) => {
        if (station.Station_JP === name) {
          if (!!station.jslodApi) returnArray.push(station);
        }
      });
    });
    return returnArray;
  };
  const [stationList, setStationList] = useState<any[][]>([[]]);
  useEffect(()=>{
    if(originalStationList.length === 0) return;
    const stationList =
      originalStationList &&
      lineList.map((d) =>
        originalStationList[d].map((a) => ({
          StationNumber: a.StationNumber,
          StationName: a.Station_JP,
        }))
      );
      setStationList(stationList)
  },[originalStationList])
   
  return (
    <TopMenuContext.Provider
      value={{ originalStationList, setOriginalStationList, getStationData, stationList }}
    >
      {children}
    </TopMenuContext.Provider>
  );
};
