import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  useLayoutEffect,
} from "react";
import { AS } from "../storageControl";
import { useStationList } from "./useStationList";
const initialState = {
  favoriteStation: [],
  setFavoriteStation: () => {},
  lodAddMigration: () => {},
};

const FavoriteStationContext = createContext(initialState);

export const useFavoriteStation = () => {
  return useContext(FavoriteStationContext);
};

export const FavoriteStationProvider = ({ children }) => {
  const [favoriteStation, setFavoriteStation] = useState([]);
  const { getStationData } = useStationList();
  const lodAddMigration = () => {
    const migration = favoriteStation.map((d) => {
      return getStationData(d[0].Station_JP);
    });
    setFavoriteStation(migration);
  };
  useEffect(() => {
    AS.getItem("favoriteStation")
      .then((d) => {
        const returnData = JSON.parse(d);
        setFavoriteStation(returnData);
      })
      .catch((d) => console.log(d));
  }, []);
  return (
    <FavoriteStationContext.Provider
      value={{ favoriteStation, setFavoriteStation, lodAddMigration }}
    >
      {children}
    </FavoriteStationContext.Provider>
  );
};
