import { use } from 'react';
import { WsClient } from '@arcblock/ws';
import { useCreation, usePrevious, useUnmount } from 'ahooks';
import { SessionContext } from '@arcblock/did-connect-react/lib/Session';
import { joinURL } from 'ufo';
import { BLOCKLET_SERVICE_PATH_PREFIX } from '@arcblock/ux/lib/Util/constant';

const client = {};

export function create(endpoint = 'admin') {
  let pathPrefix = '/';
  if (!window?.blocklet && window?.env?.apiPrefix) {
    pathPrefix = window.env.apiPrefix;
  }
  const url = joinURL(pathPrefix, BLOCKLET_SERVICE_PATH_PREFIX, endpoint);
  return new WsClient(url, {
    heartbeatIntervalMs: 100 * 1000,
  });
}

export default function getWsClient(endpoint = 'admin') {
  if (!client[endpoint]) {
    client[endpoint] = create(endpoint);
  }

  return client[endpoint];
}

export const useListenWsClient = (endpoint = 'admin') => {
  const sessionCtx = use(SessionContext);
  const { session } = sessionCtx ?? {};

  const userDid = useCreation(() => session.user?.did, [session.user]);

  const previousUserDid = usePrevious(userDid);

  useUnmount(() => {
    Object.keys(client).forEach((key) => {
      if (client[key]?.isConnected()) {
        client[key]?.disconnect();
      }
      delete client[key];
    });
  });

  if (!userDid) {
    return null;
  }

  // 同步检查：如果用户切换了，断开并重新连接所有客户端
  if (previousUserDid && previousUserDid !== userDid) {
    Object.keys(client).forEach((key) => {
      if (client[key]) {
        if (client[key].isConnected()) {
          client[key].disconnect();
        }
        // 重新连接
        client[key].connect();
      }
    });
  }
  if (!client[endpoint] && session.user) {
    client[endpoint] = getWsClient(endpoint);
    client[endpoint].connect();
  }

  return client[endpoint];
};
