
  import React from "react";
import MkdSDK from "Utils/MkdSDK";
import { AuthContext, tokenExpireError } from "Context/Auth";

const useProfile = (refresh = false) => {
  const sdk = new MkdSDK();

  const {
    state: { profile: AuthProfile },
    dispatch,
  } = React.useContext(AuthContext);
  const [profile, setProfile] = React.useState(null);

  const getProfile = React.useCallback(() => {
    (async () => {
      try {
        const result = await sdk.getProfile();
        console.log(result);
        if (!result?.error) {
          setProfile(() => result);
          dispatch({
            type: "UPDATE_PROFILE",
            payload: result,
          });
        }
      } catch (error) {
        console.log(error.message);
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, [profile]);

  React.useEffect(() => {
    if (!AuthProfile || refresh) {
      getProfile();
    } else {
      setProfile(AuthProfile);
    }
    // console.log("AuthProfile >>", AuthProfile);
  }, [AuthProfile]);

  return [profile, setProfile];
};

export default useProfile;
