import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  FC,
} from "react";
import {
  LocationObject,
  requestForegroundPermissionsAsync,
  getCurrentPositionAsync,
} from "expo-location";
import { Platform } from "react-native";
import useInterval from "@/lib/useInterval";

type initialStateType = {
  position: LocationObject | undefined;
  getCurrentPosition: () => void;
  locationStatus: boolean | null;
  getLocationPermission: () => void;
};
const initialState = {
  position: undefined,
  getCurrentPosition: () => {},
  locationStatus: null,
  getLocationPermission: () => {},
};

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

export const UserPositionProvider: FC<Props> = ({ children }) => {
  //位置情報
  const [locationStatus, setLocationStatus] = useState<boolean | null>(null);
  const [position, setPosition] = useState<LocationObject | undefined>(
    undefined
  );

  const getLocationPermission = async () => {
    return requestForegroundPermissionsAsync().then((data) => {
      setLocationStatus(
        Platform.OS == "ios"
          ? data.status == "granted"
          : data.android.accuracy == "fine"
      );
    });
  };
  const getCurrentPosition = () => {
    if (!locationStatus) return () => {};
    getCurrentPositionAsync({}).then((location) => setPosition(location));
  };
  useEffect(() => {
    if (Platform.OS == "web") return;
    getLocationPermission();
  }, []);
  useEffect(() => {
    getCurrentPosition();
  }, [locationStatus]);
  useInterval(getCurrentPosition, 5000);

  return (
    <UserPositionContext.Provider
      value={{
        position,
        getCurrentPosition,
        locationStatus,
        getLocationPermission,
      }}
    >
      {children}
    </UserPositionContext.Provider>
  );
};
