import React, { useState, createContext, useContext, useEffect } from "react";
import baseRequest from "../utils/baseRequest";
import { generateSignature } from "../utils/crypto";

const VipVisibilityContext = createContext();

export const VipVisibilityProvider = ({ children }) => {
  const [isVipVisible, setIsVipVisible] = useState(true);

  useEffect(() => {
    const init = async () => {
      try {
        const apiUrl = process.env.EXPO_PUBLIC_API_URL;
        const base = await baseRequest();
        const signature = await generateSignature({
          ...base,
        });
        const _response = await fetch(
          `${apiUrl}/api/moment/is_moment_image_encrypt_enabled?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              ...base,
            }),
          }
        );
        const _data = await _response.json();
        if (_data.ret === -1) {
          return;
        }
        setIsVipVisible(_data.data === 1 ? true : false);
      } catch (error) {
        console.error(error);
      }
    };
    init();
  }, []);

  return (
    <VipVisibilityContext.Provider value={{ isVipVisible }}>
      {children}
    </VipVisibilityContext.Provider>
  );
};

export const useVipVisibility = () => useContext(VipVisibilityContext);
