import React, { useEffect } from "react";
import { createStackNavigator } from "@react-navigation/stack";
import { CommonActions } from "@react-navigation/native";
import { AS } from "./storageControl";
import TrainBase from "./components/trainbaseview";
import HowTo from "./howto";
import Menu from "./menu";
import Setting from "./components/Settings/settings";
import { useFavoriteStation } from "./stateBox/useFavoriteStation";
import { optionData } from "./lib/stackOption";
import CurrentTrainListView from "./components/CurrentTrainListView";
import AllTrainDiagramView from "./components/AllTrainDiagramView";
import { useCurrentTrain } from "./stateBox/useCurrentTrain";
import { useNavigation } from "@react-navigation/native";
const Stack = createStackNavigator();

export function MenuPage() {
  const { favoriteStation, setFavoriteStation } = useFavoriteStation();
  const { getCurrentTrain } = useCurrentTrain();
  const navigation = useNavigation();
  const { addListener, dispatch } = navigation;
  dispatch(CommonActions.preload("positions"));
  useEffect(() => {
    AS.getItem("startPage")
      .then((res) => {
        if (res == "true") navigation.navigate("login");
      })
      .catch((e) => {
        //6.0以降false
        AS.setItem("startPage", "true");
      });
  }, []);
  useEffect(() => {
    const unsubscribe = addListener("tabPress", (e) => {
      AS.getItem("favoriteStation")
        .then((d) => {
          const returnData = JSON.parse(d);
          if (favoriteStation.toString() != d) {
            setFavoriteStation(returnData);
          }
        })
        .catch((d) => console.log(d));
    });

    return unsubscribe;
  }, [navigation]);
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="menu"
        options={{
          headerShown: false,
          gestureEnabled: true,
          headerTransparent: true,
        }}
        children={() => <Menu getCurrentTrain={getCurrentTrain} />}
      />
      <Stack.Screen
        name="setting"
        options={{
          ...optionData,
          gestureEnabled: false,
          cardOverlayEnabled: true,
        }}
        component={Setting}
      />
      <Stack.Screen
        name="trainbase"
        options={{ ...optionData }}
        component={TrainBase}
      />
      <Stack.Screen
        name="AllTrainIDList"
        options={{ ...optionData, gestureEnabled: false }}
        component={AllTrainDiagramView}
      />
      <Stack.Screen name="howto" options={optionData} component={HowTo} />
    </Stack.Navigator>
  );
}
