"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 BridgeApplicationCommandRequest_exports = {};
__export(BridgeApplicationCommandRequest_exports, {
  BridgeApplicationCommandRequest: () => BridgeApplicationCommandRequest
});
module.exports = __toCommonJS(BridgeApplicationCommandRequest_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_SendDataShared = require("../transport/SendDataShared.js");
var import_ApplicationCommandRequest = require("./ApplicationCommandRequest.js");
let BridgeApplicationCommandRequest = (() => {
  let _classDecorators = [(0, import_serial.messageTypes)(import_serial.MessageType.Request, import_serial.FunctionType.BridgeApplicationCommand), (0, import_serial.priority)(import_core.MessagePriority.Normal)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_serial.Message;
  var BridgeApplicationCommandRequest2 = class extends _classSuper {
    static {
      __name(this, "BridgeApplicationCommandRequest");
    }
    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);
      BridgeApplicationCommandRequest2 = _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) {
        this.command = options.command;
      } else {
        this._nodeId = options.nodeId;
        this.serializedCC = options.serializedCC;
      }
      this.routedBusy = options.routedBusy;
      this.frameType = options.frameType;
      this.isExploreFrame = options.isExploreFrame;
      this.isForeignFrame = options.isForeignFrame;
      this.fromForeignHomeId = options.fromForeignHomeId;
      this.ownNodeId = options.ownNodeId;
      this.targetNodeId = options.targetNodeId;
      this.rssi = options.rssi;
    }
    static from(raw, ctx) {
      const status = raw.payload[0];
      const routedBusy = !!(status & import_ApplicationCommandRequest.ApplicationCommandStatusFlags.RoutedBusy);
      let frameType;
      switch (status & import_ApplicationCommandRequest.ApplicationCommandStatusFlags.TypeMask) {
        case import_ApplicationCommandRequest.ApplicationCommandStatusFlags.TypeMulti:
          frameType = "multicast";
          break;
        case import_ApplicationCommandRequest.ApplicationCommandStatusFlags.TypeBroad:
          frameType = "broadcast";
          break;
        default:
          frameType = "singlecast";
      }
      const isExploreFrame = frameType === "broadcast" && !!(status & import_ApplicationCommandRequest.ApplicationCommandStatusFlags.Explore);
      const isForeignFrame = !!(status & import_ApplicationCommandRequest.ApplicationCommandStatusFlags.ForeignFrame);
      const fromForeignHomeId = !!(status & import_ApplicationCommandRequest.ApplicationCommandStatusFlags.ForeignHomeId);
      let offset = 1;
      const { nodeId: destinationNodeId, bytesRead: dstNodeIdBytes } = (0, import_core.parseNodeID)(raw.payload, ctx.nodeIdType, offset);
      offset += dstNodeIdBytes;
      const { nodeId: sourceNodeId, bytesRead: srcNodeIdBytes } = (0, import_core.parseNodeID)(raw.payload, ctx.nodeIdType, offset);
      offset += srcNodeIdBytes;
      const commandLength = raw.payload[offset++];
      const serializedCC = raw.payload.subarray(offset, offset + commandLength);
      offset += commandLength;
      const multicastNodesLength = raw.payload[offset];
      offset++;
      let targetNodeId;
      if (frameType === "multicast") {
        targetNodeId = (0, import_core.parseNodeBitMask)(raw.payload.subarray(offset, offset + multicastNodesLength));
      } else if (frameType === "singlecast") {
        targetNodeId = destinationNodeId;
      } else {
        targetNodeId = (0, import_core.isLongRangeNodeId)(sourceNodeId) ? import_core.NODE_ID_BROADCAST_LR : import_core.NODE_ID_BROADCAST;
      }
      offset += multicastNodesLength;
      const rssi = (0, import_SendDataShared.tryParseRSSI)(raw.payload, offset);
      return new this({
        routedBusy,
        frameType,
        isExploreFrame,
        isForeignFrame,
        fromForeignHomeId,
        nodeId: sourceNodeId,
        serializedCC,
        ownNodeId: ctx.ownNodeId,
        targetNodeId,
        rssi
      });
    }
    routedBusy;
    frameType;
    targetNodeId;
    isExploreFrame;
    isForeignFrame;
    fromForeignHomeId;
    rssi;
    ownNodeId;
    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;
    }
    // This needs to be writable or unwrapping MultiChannelCCs crashes
    command;
    _nodeId;
    getNodeId() {
      if (this.command?.isSinglecast()) {
        return this.command.nodeId;
      }
      return this._nodeId ?? super.getNodeId();
    }
    async serialize(ctx) {
      let rxStatus = 0;
      if (this.routedBusy) {
        rxStatus |= import_ApplicationCommandRequest.ApplicationCommandStatusFlags.RoutedBusy;
      }
      switch (this.frameType) {
        case "multicast":
          rxStatus |= import_ApplicationCommandRequest.ApplicationCommandStatusFlags.TypeMulti;
          break;
        case "broadcast":
          rxStatus |= import_ApplicationCommandRequest.ApplicationCommandStatusFlags.TypeBroad;
          break;
        default:
          rxStatus |= import_ApplicationCommandRequest.ApplicationCommandStatusFlags.TypeSingle;
      }
      if (this.isExploreFrame) {
        rxStatus |= import_ApplicationCommandRequest.ApplicationCommandStatusFlags.Explore;
      }
      if (this.isForeignFrame) {
        rxStatus |= import_ApplicationCommandRequest.ApplicationCommandStatusFlags.ForeignFrame;
      }
      if (this.fromForeignHomeId) {
        rxStatus |= import_ApplicationCommandRequest.ApplicationCommandStatusFlags.ForeignHomeId;
      }
      const destinationNodeId = (0, import_core.encodeNodeID)(typeof this.targetNodeId === "number" ? this.targetNodeId : 0, ctx.nodeIdType);
      const sourceNodeId = (0, import_core.encodeNodeID)(this.getNodeId() ?? 0, ctx.nodeIdType);
      const serializedCC = await this.serializeCC(ctx);
      const multicastNodeMask = typeof this.targetNodeId === "number" ? Uint8Array.from([0]) : Uint8Array.from([this.targetNodeId.length, ...this.targetNodeId]);
      this.payload = import_shared.Bytes.concat([
        [rxStatus],
        destinationNodeId,
        sourceNodeId,
        [serializedCC.length],
        serializedCC,
        multicastNodeMask,
        [import_core.RssiError.NotAvailable]
      ]);
      if (this.rssi != void 0) {
        this.payload.writeInt8(this.rssi, this.payload.length - 1);
      }
      return super.serialize(ctx);
    }
    toLogEntry() {
      const message = {};
      if (this.frameType !== "singlecast") {
        message.type = this.frameType;
      }
      if (this.targetNodeId !== this.ownNodeId) {
        if (typeof this.targetNodeId === "number") {
          message["target node"] = this.targetNodeId;
        } else if (this.targetNodeId.length === 1) {
          message["target node"] = this.targetNodeId[0];
        } else {
          message["target nodes"] = this.targetNodeId.join(", ");
        }
      }
      if (this.rssi !== void 0) {
        switch (true) {
          case this.rssi === import_core.RssiError.ReceiverSaturated:
          case this.rssi === import_core.RssiError.NoSignalDetected:
            message.RSSI = (0, import_shared.getEnumMemberName)(import_core.RssiError, this.rssi);
            break;
          // case this.rssi < RSSI_RESERVED_START:
          default:
            message.RSSI = `${this.rssi} dBm`;
            break;
        }
      }
      return {
        ...super.toLogEntry(),
        message
      };
    }
  };
  return BridgeApplicationCommandRequest2 = _classThis;
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BridgeApplicationCommandRequest
});
//# sourceMappingURL=BridgeApplicationCommandRequest.js.map
