"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __import_meta_url = typeof document === "undefined" ? new (require("url".replace("", ""))).URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var assert = __toESM(require("assert"), 1);
var import_node_dns = __toESM(require("node:dns"), 1);
var import_ws = __toESM(require("ws"), 1);
var import_winston_transport = __toESM(require("winston-transport"), 1);
var import_zwave_js = require("zwave-js");
var import_server = require("../lib/server.js");
var import_mock = require("../mock/index.js");
var import_const = require("../lib/const.js");
var import_node_module = require("node:module");
const require2 = (0, import_node_module.createRequire)(__import_meta_url);
import_node_dns.default.setDefaultResultOrder("ipv4first");
const PORT = 45001;
const createNextMessage = /* @__PURE__ */ __name((socket) => {
  let waitingListener;
  const pendingMessages = [];
  socket.on("message", (data) => {
    const msg = JSON.parse(data);
    if (!waitingListener) {
      pendingMessages.push(msg);
      return;
    }
    const listener = waitingListener;
    waitingListener = void 0;
    listener(msg);
  });
  return () => {
    if (pendingMessages.length) {
      return pendingMessages.splice(0, 1)[0];
    }
    return new Promise((resolve) => {
      waitingListener = resolve;
    });
  };
}, "createNextMessage");
const waitForResult = /* @__PURE__ */ __name(async (nextMessage, messageId) => {
  for (; ; ) {
    const message = await Promise.race([
      nextMessage(),
      new Promise((_, reject) => setTimeout(() => reject(new Error(`Timed out while waiting for result message ${messageId}`)), 5e3))
    ]);
    if (typeof message === "object" && message !== void 0 && message !== null && "type" in message && message.type === "result" && "messageId" in message && message.messageId === messageId) {
      return message;
    }
  }
}, "waitForResult");
class MockTransport extends import_winston_transport.default {
  static {
    __name(this, "MockTransport");
  }
  log(_info, next) {
    next();
  }
}
const runTest = /* @__PURE__ */ __name(async () => {
  const driver = (0, import_mock.createMockDriver)();
  const customTransport = new MockTransport();
  driver.updateLogConfig({ transports: [customTransport] });
  const server = new import_server.ZwavejsServer(driver, { port: PORT });
  await server.start(true);
  let socket = void 0;
  try {
    socket = new import_ws.default(`ws://localhost:${PORT}`);
    const nextMessage = createNextMessage(socket);
    await new Promise((resolve) => socket.once("open", resolve));
    assert.deepEqual(await nextMessage(), {
      driverVersion: import_zwave_js.libVersion,
      homeId: 1,
      serverVersion: require2("../../package.json").version,
      minSchemaVersion: import_const.minSchemaVersion,
      maxSchemaVersion: import_const.maxSchemaVersion,
      type: "version"
    });
    socket.send(JSON.stringify({
      command: "initialize",
      messageId: "initialize",
      schemaVersion: import_const.maxSchemaVersion
    }));
    assert.deepEqual(await nextMessage(), {
      type: "result",
      success: true,
      messageId: "initialize",
      result: {}
    });
    socket.send(JSON.stringify({
      messageId: "my-msg-id!",
      command: "start_listening"
    }));
    assert.deepEqual(await nextMessage(), {
      type: "result",
      success: true,
      messageId: "my-msg-id!",
      result: {
        state: {
          driver: {
            logConfig: { enabled: true, level: "debug" },
            statisticsEnabled: true,
            ready: true,
            allNodesReady: true,
            configVersion: "0.0.0-mock"
          },
          controller: { homeId: 1 },
          nodes: []
        }
      }
    });
    socket.send(JSON.stringify({
      messageId: "start-listening-logs",
      command: "driver.start_listening_logs"
    }));
    assert.deepEqual(await nextMessage(), {
      type: "result",
      success: true,
      messageId: "start-listening-logs",
      result: {}
    });
    assert.equal(driver.getLogConfig().transports?.includes(customTransport), true);
    assert.equal(driver.getLogConfig().transports?.length, 2);
    socket.send(JSON.stringify({
      messageId: "update-log-config",
      command: "driver.update_log_config",
      config: {
        enabled: true,
        level: "info",
        transports: []
      }
    }));
    assert.deepEqual(await nextMessage(), {
      type: "event",
      event: {
        source: "driver",
        event: "log config updated",
        config: {
          enabled: true,
          level: "info"
        }
      }
    });
    assert.deepEqual(await waitForResult(nextMessage, "update-log-config"), {
      type: "result",
      success: true,
      messageId: "update-log-config",
      result: {}
    });
    assert.equal(driver.getLogConfig().level, "info");
    assert.equal(driver.getLogConfig().transports?.includes(customTransport), true);
    assert.equal(driver.getLogConfig().transports?.length, 2);
    socket.send(JSON.stringify({
      messageId: "stop-listening-logs",
      command: "driver.stop_listening_logs"
    }));
    assert.deepEqual(await nextMessage(), {
      type: "result",
      success: true,
      messageId: "stop-listening-logs",
      result: {}
    });
    assert.deepEqual(driver.getLogConfig().transports, [customTransport]);
    console.log("Integration tests passed :)");
  } finally {
    if (socket) {
      socket.close();
    }
    await server.destroy();
  }
}, "runTest");
runTest();
//# sourceMappingURL=integration.js.map
