"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: 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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var SendDataBridgeMessages_exports = {};
__export(SendDataBridgeMessages_exports, {
  SendDataBridgeRequest: () => SendDataBridgeRequest,
  SendDataBridgeRequestBase: () => SendDataBridgeRequestBase,
  SendDataBridgeRequestTransmitReport: () => SendDataBridgeRequestTransmitReport,
  SendDataBridgeResponse: () => SendDataBridgeResponse,
  SendDataMulticastBridgeRequest: () => SendDataMulticastBridgeRequest,
  SendDataMulticastBridgeRequestBase: () => SendDataMulticastBridgeRequestBase,
  SendDataMulticastBridgeRequestTransmitReport: () => SendDataMulticastBridgeRequestTransmitReport,
  SendDataMulticastBridgeResponse: () => SendDataMulticastBridgeResponse
});
module.exports = __toCommonJS(SendDataBridgeMessages_exports);
var import_tslib = require("tslib");
var import_core = require("@zwave-js/core");
var import_serial = require("@zwave-js/serial");
var import_shared = require("@zwave-js/shared");
var import_math = require("alcalzone-shared/math");
var import_ApplicationCommandRequest = require("../application/ApplicationCommandRequest.js");
var import_BridgeApplicationCommandRequest = require("../application/BridgeApplicationCommandRequest.js");
var import_utils = require("../utils.js");
var import_SendDataMessages = require("./SendDataMessages.js");
var import_SendDataShared = require("./SendDataShared.js");
let SendDataBridgeRequestBase = (() => {
  let _classDecorators = [(0, import_serial.messageTypes)(import_serial.MessageType.Request, import_serial.FunctionType.SendDataBridge), (0, import_serial.priority)(import_core.MessagePriority.Normal)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_serial.Message;
  var SendDataBridgeRequestBase2 = class extends _classSuper {
    static {
      __name(this, "SendDataBridgeRequestBase");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      (0, import_tslib.__esDecorate)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      SendDataBridgeRequestBase2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    static from(raw, ctx) {
      if (ctx.origin === import_serial.MessageOrigin.Host) {
        return SendDataBridgeRequest.from(raw, ctx);
      } else {
        return SendDataBridgeRequestTransmitReport.from(raw, ctx);
      }
    }
  };
  return SendDataBridgeRequestBase2 = _classThis;
})();
let SendDataBridgeRequest = (() => {
  let _classDecorators = [(0, import_serial.expectedResponse)(import_serial.FunctionType.SendDataBridge), (0, import_serial.expectedCallback)(import_serial.FunctionType.SendDataBridge)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = SendDataBridgeRequestBase;
  var SendDataBridgeRequest2 = class extends _classSuper {
    static {
      __name(this, "SendDataBridgeRequest");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      (0, import_tslib.__esDecorate)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      SendDataBridgeRequest2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    constructor(options) {
      super(options);
      if ("command" in options) {
        if (!options.command.isSinglecast() && !options.command.isBroadcast()) {
          throw new import_core.ZWaveError(`SendDataBridgeRequest can only be used for singlecast and broadcast CCs`, import_core.ZWaveErrorCodes.Argument_Invalid);
        }
        this.command = options.command;
        this._nodeId = options.command.nodeId;
      } else {
        this._nodeId = options.nodeId;
        this.serializedCC = options.serializedCC;
      }
      this.sourceNodeId = options.sourceNodeId;
      this.transmitOptions = options.transmitOptions ?? import_core.TransmitOptions.DEFAULT;
      if (options.maxSendAttempts != void 0) {
        this.maxSendAttempts = options.maxSendAttempts;
      }
    }
    static from(raw, ctx) {
      let offset = 0;
      let parseResult = (0, import_core.parseNodeID)(raw.payload, ctx.nodeIdType);
      const sourceNodeId = parseResult.nodeId;
      offset += parseResult.bytesRead;
      parseResult = (0, import_core.parseNodeID)(raw.payload, ctx.nodeIdType, offset);
      const destinationNodeId = parseResult.nodeId;
      offset += parseResult.bytesRead;
      const ccLength = raw.payload[offset++];
      const serializedCC = raw.payload.slice(offset, offset + ccLength);
      offset += ccLength;
      const transmitOptions = raw.payload[offset++];
      offset += 4;
      const callbackId = raw.payload[offset++];
      return new this({
        sourceNodeId,
        nodeId: destinationNodeId,
        serializedCC,
        transmitOptions,
        callbackId
      });
    }
    /** Which Node ID this command originates from */
    sourceNodeId;
    /** The command this message contains */
    command;
    /** Options regarding the transmission of the message */
    transmitOptions;
    _maxSendAttempts = 1;
    /** The number of times the driver may try to send this message */
    get maxSendAttempts() {
      return this._maxSendAttempts;
    }
    set maxSendAttempts(value) {
      this._maxSendAttempts = (0, import_math.clamp)(value, 1, import_SendDataMessages.MAX_SEND_ATTEMPTS);
    }
    _nodeId;
    getNodeId() {
      return this.command?.nodeId ?? this._nodeId;
    }
    serializedCC;
    async serializeCC(ctx) {
      if (!this.serializedCC) {
        if (!this.command) {
          throw new import_core.ZWaveError(`Cannot serialize a ${this.constructor.name} without a command`, import_core.ZWaveErrorCodes.Argument_Invalid);
        }
        this.serializedCC = await this.command.serialize(ctx);
      }
      return this.serializedCC;
    }
    prepareRetransmission() {
      this.command?.prepareRetransmission();
      this.serializedCC = void 0;
      this.callbackId = void 0;
    }
    async serialize(ctx) {
      this.assertCallbackId();
      const sourceNodeId = (0, import_core.encodeNodeID)(this.sourceNodeId, ctx.nodeIdType);
      const destinationNodeId = (0, import_core.encodeNodeID)(this.command?.nodeId ?? this._nodeId, ctx.nodeIdType);
      const serializedCC = await this.serializeCC(ctx);
      this.payload = import_shared.Bytes.concat([
        sourceNodeId,
        destinationNodeId,
        [serializedCC.length],
        serializedCC,
        [this.transmitOptions, 0, 0, 0, 0, this.callbackId]
      ]);
      return super.serialize(ctx);
    }
    toLogEntry() {
      return {
        ...super.toLogEntry(),
        message: {
          "source node id": this.sourceNodeId,
          "transmit options": (0, import_shared.num2hex)(this.transmitOptions),
          "callback id": this.callbackId ?? "(not set)"
        }
      };
    }
    expectsNodeUpdate(ctx) {
      return (
        // We can only answer this if the command is known
        this.command != void 0 && this.command.isSinglecast() && this.command.expectsCCResponse(ctx)
      );
    }
    isExpectedNodeUpdate(ctx, msg) {
      return (
        // We can only answer this if the command is known
        this.command != void 0 && (msg instanceof import_ApplicationCommandRequest.ApplicationCommandRequest || msg instanceof import_BridgeApplicationCommandRequest.BridgeApplicationCommandRequest) && (0, import_utils.containsCC)(msg) && this.command.isExpectedCCResponse(ctx, msg.command)
      );
    }
  };
  return SendDataBridgeRequest2 = _classThis;
})();
class SendDataBridgeRequestTransmitReport extends SendDataBridgeRequestBase {
  static {
    __name(this, "SendDataBridgeRequestTransmitReport");
  }
  constructor(options) {
    super(options);
    this.callbackId = options.callbackId;
    this.transmitStatus = options.transmitStatus;
    this.txReport = options.txReport;
  }
  static from(raw, _ctx) {
    const callbackId = raw.payload[0];
    const transmitStatus = raw.payload[1];
    const txReport = (0, import_SendDataShared.parseTXReport)(transmitStatus !== import_core.TransmitStatus.NoAck, raw.payload.subarray(2));
    return new this({
      callbackId,
      transmitStatus,
      txReport
    });
  }
  transmitStatus;
  txReport;
  isOK() {
    return this.transmitStatus === import_core.TransmitStatus.OK;
  }
  serialize(ctx) {
    this.assertCallbackId();
    this.payload = import_shared.Bytes.from([this.callbackId, this.transmitStatus]);
    if (this.txReport) {
      this.payload = import_shared.Bytes.concat([
        this.payload,
        (0, import_SendDataShared.encodeTXReport)(this.txReport)
      ]);
    }
    return super.serialize(ctx);
  }
  toLogEntry() {
    return {
      ...super.toLogEntry(),
      message: {
        "callback id": this.callbackId ?? "(not set)",
        "transmit status": (0, import_shared.getEnumMemberName)(import_core.TransmitStatus, this.transmitStatus) + (this.txReport ? `, took ${this.txReport.txTicks * 10} ms` : ""),
        // Show TX report fields for OK and NoAck (NoAck still provides useful routing info)
        ...this.txReport && (this.transmitStatus === import_core.TransmitStatus.OK || this.transmitStatus === import_core.TransmitStatus.NoAck) ? (0, import_SendDataShared.txReportToMessageRecord)(this.txReport) : {}
      }
    };
  }
}
let SendDataBridgeResponse = (() => {
  let _classDecorators = [(0, import_serial.messageTypes)(import_serial.MessageType.Response, import_serial.FunctionType.SendDataBridge)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_serial.Message;
  var SendDataBridgeResponse2 = class extends _classSuper {
    static {
      __name(this, "SendDataBridgeResponse");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      (0, import_tslib.__esDecorate)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      SendDataBridgeResponse2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    constructor(options) {
      super(options);
      this.wasSent = options.wasSent;
    }
    static from(raw, _ctx) {
      const wasSent = raw.payload[0] !== 0;
      return new this({
        wasSent
      });
    }
    isOK() {
      return this.wasSent;
    }
    wasSent;
    toLogEntry() {
      return {
        ...super.toLogEntry(),
        message: { "was sent": this.wasSent }
      };
    }
  };
  return SendDataBridgeResponse2 = _classThis;
})();
let SendDataMulticastBridgeRequestBase = (() => {
  let _classDecorators = [(0, import_serial.messageTypes)(import_serial.MessageType.Request, import_serial.FunctionType.SendDataMulticastBridge), (0, import_serial.priority)(import_core.MessagePriority.Normal)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_serial.Message;
  var SendDataMulticastBridgeRequestBase2 = class extends _classSuper {
    static {
      __name(this, "SendDataMulticastBridgeRequestBase");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      (0, import_tslib.__esDecorate)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      SendDataMulticastBridgeRequestBase2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    static from(raw, ctx) {
      if (ctx.origin === import_serial.MessageOrigin.Host) {
        return SendDataMulticastBridgeRequest.from(raw, ctx);
      } else {
        return SendDataMulticastBridgeRequestTransmitReport.from(raw, ctx);
      }
    }
  };
  return SendDataMulticastBridgeRequestBase2 = _classThis;
})();
let SendDataMulticastBridgeRequest = (() => {
  let _classDecorators = [(0, import_serial.expectedResponse)(import_serial.FunctionType.SendDataMulticastBridge), (0, import_serial.expectedCallback)(import_serial.FunctionType.SendDataMulticastBridge)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = SendDataMulticastBridgeRequestBase;
  var SendDataMulticastBridgeRequest2 = class extends _classSuper {
    static {
      __name(this, "SendDataMulticastBridgeRequest");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      (0, import_tslib.__esDecorate)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      SendDataMulticastBridgeRequest2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    constructor(options) {
      super(options);
      if ("command" in options) {
        if (!options.command.isMulticast()) {
          throw new import_core.ZWaveError(`SendDataMulticastBridgeRequest can only be used for multicast CCs`, import_core.ZWaveErrorCodes.Argument_Invalid);
        } else if (options.command.nodeId.length === 0) {
          throw new import_core.ZWaveError(`At least one node must be targeted`, import_core.ZWaveErrorCodes.Argument_Invalid);
        } else if (options.command.nodeId.some((n) => n < 1 || n > import_core.MAX_NODES)) {
          throw new import_core.ZWaveError(`All node IDs must be between 1 and ${import_core.MAX_NODES}!`, import_core.ZWaveErrorCodes.Argument_Invalid);
        }
        this.command = options.command;
        this.nodeIds = this.command.nodeId;
      } else {
        this.nodeIds = options.nodeIds;
        this.serializedCC = options.serializedCC;
      }
      this.sourceNodeId = options.sourceNodeId;
      this.transmitOptions = options.transmitOptions ?? import_core.TransmitOptions.DEFAULT;
      if (options.maxSendAttempts != void 0) {
        this.maxSendAttempts = options.maxSendAttempts;
      }
    }
    static from(raw, ctx) {
      const { nodeId: sourceNodeId, bytesRead } = (0, import_core.parseNodeID)(raw.payload, ctx.nodeIdType);
      let offset = bytesRead;
      const destinationNodeIdCount = raw.payload[offset++];
      const nodeIds = [];
      for (let i = 0; i < destinationNodeIdCount; i++) {
        const { nodeId, bytesRead: bytesRead2 } = (0, import_core.parseNodeID)(raw.payload, ctx.nodeIdType, offset);
        nodeIds.push(nodeId);
        offset += bytesRead2;
      }
      const ccLength = raw.payload[offset++];
      const serializedCC = raw.payload.slice(offset, offset + ccLength);
      offset += ccLength;
      const transmitOptions = raw.payload[offset++];
      const callbackId = raw.payload[offset++];
      return new this({
        sourceNodeId,
        nodeIds,
        serializedCC,
        transmitOptions,
        callbackId
      });
    }
    /** Which Node ID this command originates from */
    sourceNodeId;
    /** The command this message contains */
    command;
    /** Options regarding the transmission of the message */
    transmitOptions;
    _maxSendAttempts = 1;
    /** The number of times the driver may try to send this message */
    get maxSendAttempts() {
      return this._maxSendAttempts;
    }
    set maxSendAttempts(value) {
      this._maxSendAttempts = (0, import_math.clamp)(value, 1, import_SendDataMessages.MAX_SEND_ATTEMPTS);
    }
    nodeIds;
    getNodeId() {
      return void 0;
    }
    serializedCC;
    async serializeCC(ctx) {
      if (!this.serializedCC) {
        if (!this.command) {
          throw new import_core.ZWaveError(`Cannot serialize a ${this.constructor.name} without a command`, import_core.ZWaveErrorCodes.Argument_Invalid);
        }
        this.serializedCC = await this.command.serialize(ctx);
      }
      return this.serializedCC;
    }
    prepareRetransmission() {
      this.command?.prepareRetransmission();
      this.serializedCC = void 0;
      this.callbackId = void 0;
    }
    async serialize(ctx) {
      this.assertCallbackId();
      const serializedCC = await this.serializeCC(ctx);
      const sourceNodeId = (0, import_core.encodeNodeID)(this.sourceNodeId, ctx.nodeIdType);
      const destinationNodeIDs = (this.command?.nodeId ?? this.nodeIds).map((id) => (0, import_core.encodeNodeID)(id, ctx.nodeIdType));
      this.payload = import_shared.Bytes.concat([
        sourceNodeId,
        // # of target nodes, not # of bytes
        [destinationNodeIDs.length],
        ...destinationNodeIDs,
        [serializedCC.length],
        // payload
        serializedCC,
        [this.transmitOptions, this.callbackId]
      ]);
      return super.serialize(ctx);
    }
    toLogEntry() {
      return {
        ...super.toLogEntry(),
        message: {
          "source node id": this.sourceNodeId,
          "target nodes": (this.command?.nodeId ?? this.nodeIds).join(", "),
          "transmit options": (0, import_shared.num2hex)(this.transmitOptions),
          "callback id": this.callbackId ?? "(not set)"
        }
      };
    }
  };
  return SendDataMulticastBridgeRequest2 = _classThis;
})();
class SendDataMulticastBridgeRequestTransmitReport extends SendDataMulticastBridgeRequestBase {
  static {
    __name(this, "SendDataMulticastBridgeRequestTransmitReport");
  }
  constructor(options) {
    super(options);
    this.callbackId = options.callbackId;
    this.transmitStatus = options.transmitStatus;
  }
  static from(raw, _ctx) {
    const callbackId = raw.payload[0];
    const transmitStatus = raw.payload[1];
    return new this({
      callbackId,
      transmitStatus
    });
  }
  transmitStatus;
  isOK() {
    return this.transmitStatus === import_core.TransmitStatus.OK;
  }
  toLogEntry() {
    return {
      ...super.toLogEntry(),
      message: {
        "callback id": this.callbackId ?? "(not set)",
        "transmit status": (0, import_shared.getEnumMemberName)(import_core.TransmitStatus, this.transmitStatus)
      }
    };
  }
}
let SendDataMulticastBridgeResponse = (() => {
  let _classDecorators = [(0, import_serial.messageTypes)(import_serial.MessageType.Response, import_serial.FunctionType.SendDataMulticastBridge)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_serial.Message;
  var SendDataMulticastBridgeResponse2 = class extends _classSuper {
    static {
      __name(this, "SendDataMulticastBridgeResponse");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      (0, import_tslib.__esDecorate)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      SendDataMulticastBridgeResponse2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    constructor(options) {
      super(options);
      this.wasSent = options.wasSent;
    }
    static from(raw, _ctx) {
      const wasSent = raw.payload[0] !== 0;
      return new this({
        wasSent
      });
    }
    isOK() {
      return this.wasSent;
    }
    wasSent;
    toLogEntry() {
      return {
        ...super.toLogEntry(),
        message: { "was sent": this.wasSent }
      };
    }
  };
  return SendDataMulticastBridgeResponse2 = _classThis;
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SendDataBridgeRequest,
  SendDataBridgeRequestBase,
  SendDataBridgeRequestTransmitReport,
  SendDataBridgeResponse,
  SendDataMulticastBridgeRequest,
  SendDataMulticastBridgeRequestBase,
  SendDataMulticastBridgeRequestTransmitReport,
  SendDataMulticastBridgeResponse
});
//# sourceMappingURL=SendDataBridgeMessages.js.map
