import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Context/Global";
import MkdSDK from "Utils/MkdSDK";
import { useContext, useEffect, useState } from "react";

export default function useSettings() {
  const { dispatch: authDispatch } = useContext(AuthContext);
  const { dispatch: globalDispatch } = useContext(GlobalContext);
  const [settings, setSettings] = useState([]);
  const [loading, setLoading] = useState(false);

  async function fetchSettings() {
    setLoading(true);
    try {
      const sdk = new MkdSDK();
      const result = await sdk.callRawAPI(`/v4/api/records/setting`);
      setSettings(result.list);
    } catch (err) {
      tokenExpireError(authDispatch, err.message);
      showToast(globalDispatch, err.message, 5000, "error");
    }
    setLoading(false);
  }

  useEffect(() => {
    fetchSettings();
  }, []);

  return { settings, refetch: fetchSettings, loading };
}
