/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
import { parseBigIntAwareJson, toBigIntAwareJson } from "./json-utils.js";
class Connection {
  /**
   * Create a new connection.
   * @param ws_server_url WebSocket server URL
   * @param wsFactory Optional factory function to create WebSocket instances.
   *                  If not provided, uses the global WebSocket constructor.
   */
  constructor(ws_server_url, wsFactory) {
    this.ws_server_url = ws_server_url;
    this.ws_server_url = ws_server_url;
    this.wsFactory = wsFactory ?? ((url) => new WebSocket(url));
  }
  serverInfo = void 0;
  socket;
  wsFactory;
  get connected() {
    return this.socket?.readyState === 1;
  }
  async connect(onMessage, onConnectionLost) {
    if (this.socket) {
      throw new Error("Already connected");
    }
    console.debug("Trying to connect");
    return new Promise((resolve, reject) => {
      this.socket = this.wsFactory(this.ws_server_url);
      this.socket.onopen = () => {
        console.log("WebSocket Connected");
      };
      this.socket.onclose = () => {
        console.log("WebSocket Closed");
        this.socket = void 0;
        this.serverInfo = void 0;
        onConnectionLost();
      };
      this.socket.onerror = (error) => {
        console.error("WebSocket Error: ", error);
        reject(new Error("WebSocket Error"));
      };
      this.socket.onmessage = (event) => {
        const dataStr = typeof event.data === "string" ? event.data : String(event.data);
        const data = parseBigIntAwareJson(dataStr);
        console.log("WebSocket OnMessage", data);
        if (!this.serverInfo) {
          this.serverInfo = data;
          resolve();
          return;
        }
        onMessage(data);
      };
    });
  }
  disconnect() {
    if (this.socket) {
      this.socket.close();
      this.socket = void 0;
    }
    this.serverInfo = void 0;
  }
  sendMessage(message) {
    if (!this.socket) {
      throw new Error("Not connected");
    }
    console.log("WebSocket send message", message);
    this.socket.send(toBigIntAwareJson(message));
  }
}
var connection_default = Connection;
export {
  Connection,
  connection_default as default
};
//# sourceMappingURL=connection.js.map
