import { use as c } from "react";
import { WsClient as f } from "@arcblock/ws";
import { useCreation as u, usePrevious as m, useUnmount as a } from "ahooks";
import { SessionContext as l } from "@arcblock/did-connect-react/lib/Session";
import { joinURL as C } from "ufo";
import { BLOCKLET_SERVICE_PATH_PREFIX as d } from "@arcblock/ux/lib/Util/constant";
const e = {};
function w(t = "admin") {
  let r = "/";
  !window?.blocklet && window?.env?.apiPrefix && (r = window.env.apiPrefix);
  const s = C(r, d, t);
  return new f(s, {
    heartbeatIntervalMs: 100 * 1e3
  });
}
function x(t = "admin") {
  return e[t] || (e[t] = w(t)), e[t];
}
const L = (t = "admin") => {
  const r = c(l), { session: s } = r ?? {}, n = u(() => s.user?.did, [s.user]), o = m(n);
  return a(() => {
    Object.keys(e).forEach((i) => {
      e[i]?.isConnected() && e[i]?.disconnect(), delete e[i];
    });
  }), n ? (o && o !== n && Object.keys(e).forEach((i) => {
    e[i] && (e[i].isConnected() && e[i].disconnect(), e[i].connect());
  }), !e[t] && s.user && (e[t] = x(t), e[t].connect()), e[t]) : null;
};
export {
  w as create,
  x as default,
  L as useListenWsClient
};
