"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useSubscription = useSubscription;
var _ws = require("@arcblock/ws");
var _get = _interopRequireDefault(require("lodash/get"));
var _react = require("react");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const RELAY_SOCKET_PREFIX = "/.well-known/service/relay";
const getAppId = () => (0, _get.default)(window, "blocklet.appPid") || (0, _get.default)(window, "blocklet.appId") || "";
const getRelayChannel = token => `relay:${getAppId()}:${token}`;
const getRelayProtocol = () => window.location.protocol === "https:" ? "wss:" : "ws:";
const getSocketHost = () => new URL(window.location.href).host;
function useSubscription(channel) {
  const socket = (0, _react.useRef)(null);
  const subscription = (0, _react.useRef)(null);
  (0, _react.useEffect)(() => {
    if (getAppId()) {
      const needReconnect = !socket.current || socket.current.isConnected() === false;
      if (needReconnect) {
        socket.current = new _ws.WsClient(`${getRelayProtocol()}//${getSocketHost()}${RELAY_SOCKET_PREFIX}`, {
          longpollerTimeout: 5e3,
          // connection timeout
          heartbeatIntervalMs: 30 * 1e3
        });
        socket.current.connect();
      }
    }
    return () => {
      if (socket.current) {
        socket.current.disconnect();
        socket.current = null;
      }
    };
  }, []);
  (0, _react.useEffect)(() => {
    if (channel) {
      let needSubscription = false;
      if (subscription.current) {
        if (subscription.current.channel !== channel) {
          socket.current?.unsubscribe(getRelayChannel(subscription.current.channel));
          needSubscription = true;
        }
      } else {
        needSubscription = true;
      }
      if (needSubscription && socket.current) {
        subscription.current = socket.current.subscribe(getRelayChannel(channel));
        subscription.current.channel = channel;
      }
    }
    return () => {
      if (subscription.current) {
        socket.current?.unsubscribe(getRelayChannel(subscription.current.channel));
        subscription.current = null;
      }
    };
  }, [channel]);
  return subscription.current;
}