import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  FC,
} from "react";
import { getStationList } from "../lib/getStationList";
import { lineList } 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 StationListContext = createContext<initialStateType>(initialState);
type Props = {
  children: React.ReactNode;
};
export const useStationList = () => {
  return useContext(StationListContext);
};

export const StationListProvider: 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 (
    <StationListContext.Provider
      value={{ originalStationList, setOriginalStationList, getStationData, stationList }}
    >
      {children}
    </StationListContext.Provider>
  );
};
