text: import React, { createContext, useState, useEffect } from "react";
  import { sendNotificationToken, getNotifications, login } from "network";
  
  import RNIAP, { clearTransactionIOS } from "react-native-iap";
  import * as Notifications from "expo-notifications";
  import Constants from "expo-constants";
  import { getData, storeData } from "constants";
  import { Alert } from "react-native";
  
  const registerForPushNotificationsAsync = async (userToken) => {
    if (!Constants.isDevice) return;
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== "granted") {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== "granted") return;
    const token = (
      await Notifications.getExpoPushTokenAsync({
        experienceId: "@nextriesh/isneaks-app",
      })
    ).data;
    if (userToken === token) return;
    await sendNotificationToken(token);
  
    if (Platform.OS === "android") {
      Notifications.setNotificationChannelAsync("default", {
        name: "default",
        importance: Notifications.AndroidImportance.MAX,
        vibrationPattern: [0, 250, 250, 250],
        lightColor: "#FF231F7C",
      });
    }
  };
  
  export const UserContext = createContext();
  export const UserContextProvider = ({ children }) => {
    const [user, setUser] = useState(null);
    const [hasSubbed, setHasSubbed] = useState(false);
    const [isRecoveringSession, setIsRecoveringSession] = useState(true);
    const [notifications, setNotifications] = useState([]);
  
    const handleNewNotifications = async () => {
      const newNotifications = (await getNotifications(0)) || [];
      const currentlyReadNotifications = await getData("readNotifications");
      if (!currentlyReadNotifications) {
        await storeData("readNotifications", []);
        setNotifications([]);
      } else
        setNotifications(
          (newNotifications || []).filter(
            (elem) => !currentlyReadNotifications.includes(elem.id)
          )
        );
    };
  
    const setReadNotification = async (id) => {
      if (isNaN(id)) return;
      const currentlyReadNotifications = await getData("readNotifications");
      if (!currentlyReadNotifications) await storeData("readNotifications", []);
      await storeData("readNotifications", [...currentlyReadNotifications, id]);
      setNotifications(notifications.filter((elem) => elem.id !== id));
    };
  
    const readAllNotifications = async () => {
      const currentlyReadNotifications = await getData("readNotifications");
      if (!currentlyReadNotifications) await storeData("readNotifications", []);
      const currentNotificationsIds = notifications.map((elem) => elem.id);
      await storeData("readNotifications", [
        ...currentlyReadNotifications,
        ...currentNotificationsIds,
      ]);
      setNotifications([]);
    };
  
    const recoverUserSession = async () => {
      const userData = await getData("userAuthentificationData");
      if (!userData) return setIsRecoveringSession(false);
      const { email, password } = userData;
  
      if (!email || !password) return setIsRecoveringSession(false);
  
      const user = await login({ email, password });
      if (user && user.email) setUser(user);
      setIsRecoveringSession(false);
    };
  
    /* A SUPPRIMER APRES DEVELOPPEMENT */
    const resetNotifications = async () => {
      await storeData("readNotifications", []);
    };
    /* A SUPPRIMER */
  
    const initPayments = async () => {
      if (hasSubbed) return console.log("already subbed to payment listener!");
      const conn = await RNIAP.initConnection();
      if (!conn) return;
      await clearTransactionIOS();
  
      RNIAP.purchaseUpdatedListener(async (purchase) => {
        await RNIAP.finishTransaction(purchase, false);
      });
  
      setHasSubbed(true);
      await recoverUserSession();
    };
  
    useEffect(() => {
      if (user !== null) {
        setIsRecoveringSession(false);
        handleNewNotifications();
        registerForPushNotificationsAsync(user.notificationToken);
      } else {
        if (Constants.isDevice) {
          initPayments();
        } else recoverUserSession();
      }
    }, [user]);
  
    return (
      <UserContext.Provider
        value={{
          user,
          setUser,
          isConnected: !!user,
          notifications,
          setReadNotification,
          readAllNotifications,
          handleNewNotifications,
          isRecoveringSession,
        }}
      >
        {children}
      </UserContext.Provider>
    );
  };
  