import { useRef as h, useEffect as F } from "react";
import { actionsType as n } from "../types.js";
import { useNetwork as A, getPropertyByString as P } from "@m4l/core";
function b(C) {
  const {
    state: t,
    dispatch: r,
    endPoint: a,
    timeout: i,
    isExternalUrl: s,
    parms: o,
    responseToCamelCase: c,
    isRemote: u,
    resultField: f = "data"
  } = C, { networkOperation: l } = A(), e = h(null), p = h(t.fireFetchCount);
  F(() => {
    r({ type: n.SET_PARAMS, payload: o });
  }, [o, r]), F(() => {
    let y = !1;
    if (p.current !== t.fireFetchCount)
      return p.current = t.fireFetchCount, t.fireFetchCount > 0 && (e.current && e.current.abort(), e.current = new AbortController(), l({
        method: "GET",
        endPoint: a,
        timeout: i,
        isExternalUrl: s,
        parms: { ...o, ...t.queryParams },
        responseToCamelCase: c,
        isRemote: u,
        signal: e.current.signal
      }).then((O) => {
        if (y)
          return;
        const m = P(O, f), d = Array.isArray(m) ? m : [];
        r({
          type: n.FINISH_LOAD_OPTIONS,
          payload: { options: d }
        });
      }).catch(() => {
        r({
          type: n.FINISH_LOAD_OPTIONS,
          payload: {}
        });
      })), () => {
        y = !0, e.current && e.current.abort();
      };
  }, [
    r,
    a,
    s,
    u,
    l,
    o,
    c,
    f,
    t.fireFetchCount,
    t.queryParams,
    i
  ]);
}
export {
  b as useFetchOptions
};
