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

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

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;
    
  };

  return (
    <StationListContext.Provider
      value={{ originalStationList, setOriginalStationList, getStationData }}
    >
      {children}
    </StationListContext.Provider>
  );
};
