"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 SupervisionCC_exports = {};
__export(SupervisionCC_exports, {
  SupervisionCC: () => SupervisionCC,
  SupervisionCCAPI: () => SupervisionCCAPI,
  SupervisionCCGet: () => SupervisionCCGet,
  SupervisionCCReport: () => SupervisionCCReport,
  SupervisionCCValues: () => import_CCValues_generated.SupervisionCCValues
});
module.exports = __toCommonJS(SupervisionCC_exports);
var import_tslib = require("tslib");
var import_core = require("@zwave-js/core");
var import_shared = require("@zwave-js/shared");
var import_API = require("../lib/API.js");
var import_CommandClass = require("../lib/CommandClass.js");
var import_CommandClassDecorators = require("../lib/CommandClassDecorators.js");
var import_Types = require("../lib/_Types.js");
var import_CCValues_generated = require("./_CCValues.generated.js");
let SupervisionCCAPI = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.API)(import_core.CommandClasses.Supervision)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_API.PhysicalCCAPI;
  var SupervisionCCAPI2 = class extends _classSuper {
    static {
      __name(this, "SupervisionCCAPI");
    }
    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);
      SupervisionCCAPI2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    supportsCommand(cmd) {
      switch (cmd) {
        case import_Types.SupervisionCommand.Get:
        case import_Types.SupervisionCommand.Report:
          return true;
      }
      return super.supportsCommand(cmd);
    }
    async sendReport(options) {
      const { encapsulationFlags = import_core.EncapsulationFlags.None, lowPriority = false, ...cmdOptions } = options;
      const cc = new SupervisionCCReport({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        ...cmdOptions
      });
      cc.encapsulationFlags = encapsulationFlags;
      try {
        await this.host.sendCommand(cc, {
          ...this.commandOptions,
          // Supervision Reports must be prioritized over normal messages
          priority: lowPriority ? import_core.MessagePriority.ImmediateLow : import_core.MessagePriority.Immediate,
          // But we don't want to wait for an ACK because this can lock up the network for seconds
          // if the target node is asleep or unreachable
          transmitOptions: import_core.TransmitOptions.DEFAULT_NOACK,
          // Only try sending the report once. If it fails, the node will ask again
          maxSendAttempts: 1,
          // Don't keep the transaction alive to verify S2 delivery, or receiving
          // other commands from the node may interfere with it
          s2VerifyDelivery: false
        });
      } catch (e) {
        if ((0, import_core.isTransmissionError)(e)) {
          return;
        } else {
          throw e;
        }
      }
    }
  };
  return SupervisionCCAPI2 = _classThis;
})();
let SupervisionCC = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.commandClass)(import_core.CommandClasses.Supervision), (0, import_CommandClassDecorators.implementedVersion)(2)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_CommandClass.CommandClass;
  var SupervisionCC2 = class extends _classSuper {
    static {
      __name(this, "SupervisionCC");
    }
    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);
      SupervisionCC2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    /** Tests if a command should be supervised and thus requires encapsulation */
    static requiresEncapsulation(cc) {
      return !!(cc.encapsulationFlags & import_core.EncapsulationFlags.Supervision) && !(cc instanceof SupervisionCCGet) && !(cc instanceof SupervisionCCReport);
    }
    /** Encapsulates a command that targets a specific endpoint */
    static encapsulate(cc, sessionId, requestStatusUpdates = true) {
      if (!cc.isSinglecast()) {
        throw new import_core.ZWaveError(`Supervision is only possible for singlecast commands!`, import_core.ZWaveErrorCodes.Argument_Invalid);
      }
      const ret = new SupervisionCCGet({
        nodeId: cc.nodeId,
        // Supervision CC is wrapped inside MultiChannel CCs, so the endpoint must be copied
        endpointIndex: cc.endpointIndex,
        encapsulated: cc,
        sessionId,
        requestStatusUpdates
      });
      ret.encapsulationFlags = cc.encapsulationFlags & ~import_core.EncapsulationFlags.Supervision;
      return ret;
    }
    /**
     * Given a CC instance, this returns the Supervision session ID which is used for this command.
     * Returns `undefined` when there is no session ID or the command was sent as multicast.
     */
    static getSessionId(command) {
      if (command.isEncapsulatedWith(import_core.CommandClasses.Supervision, import_Types.SupervisionCommand.Get)) {
        const supervisionEncapsulation = command.getEncapsulatingCC(import_core.CommandClasses.Supervision, import_Types.SupervisionCommand.Get);
        if (supervisionEncapsulation.frameType !== "broadcast" && supervisionEncapsulation.frameType !== "multicast") {
          return supervisionEncapsulation.sessionId;
        }
      }
    }
    /**
     * Returns whether a node supports the given CC with Supervision encapsulation.
     */
    static getCCSupportedWithSupervision(ctx, endpoint, ccId) {
      return ctx.getValueDB(endpoint.nodeId).getValue(import_CCValues_generated.SupervisionCCValues.ccSupported(ccId).endpoint(endpoint.index)) ?? true;
    }
    /**
     * Remembers whether a node supports the given CC with Supervision encapsulation.
     */
    static setCCSupportedWithSupervision(ctx, endpoint, ccId, supported) {
      ctx.getValueDB(endpoint.nodeId).setValue(import_CCValues_generated.SupervisionCCValues.ccSupported(ccId).endpoint(endpoint.index), supported);
    }
    /** Returns whether this is a valid command to send supervised */
    static mayUseSupervision(ctx, command) {
      if (!command.isSinglecast())
        return false;
      if (command.expectsCCResponse(ctx))
        return false;
      const node = command.getNode(ctx);
      if (!node)
        return false;
      const endpoint = command.getEndpoint(ctx);
      if (!endpoint)
        return false;
      return (
        // ... the node supports it
        node.supportsCC(import_core.CommandClasses.Supervision) && (0, import_CommandClassDecorators.shouldUseSupervision)(command) && SupervisionCC2.getCCSupportedWithSupervision(ctx, endpoint, command.ccId)
      );
    }
  };
  return SupervisionCC2 = _classThis;
})();
let SupervisionCCReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.SupervisionCommand.Report)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = SupervisionCC;
  var SupervisionCCReport2 = class extends _classSuper {
    static {
      __name(this, "SupervisionCCReport");
    }
    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);
      SupervisionCCReport2 = _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.moreUpdatesFollow = options.moreUpdatesFollow;
      this.requestWakeUpOnDemand = !!options.requestWakeUpOnDemand;
      this.sessionId = options.sessionId;
      this.status = options.status;
      if (options.status === import_core.SupervisionStatus.Working) {
        this.duration = options.duration;
      } else {
        this.duration = new import_core.Duration(0, "seconds");
      }
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 3);
      const moreUpdatesFollow = !!(raw.payload[0] & 128);
      const requestWakeUpOnDemand = !!(raw.payload[0] & 64);
      const sessionId = raw.payload[0] & 63;
      const status = raw.payload[1];
      if (status === import_core.SupervisionStatus.Working) {
        const duration = import_core.Duration.parseReport(raw.payload[2]) ?? new import_core.Duration(0, "seconds");
        return new this({
          nodeId: ctx.sourceNodeId,
          moreUpdatesFollow,
          requestWakeUpOnDemand,
          sessionId,
          status,
          duration
        });
      } else {
        return new this({
          nodeId: ctx.sourceNodeId,
          moreUpdatesFollow,
          requestWakeUpOnDemand,
          sessionId,
          status
        });
      }
    }
    moreUpdatesFollow;
    requestWakeUpOnDemand;
    sessionId;
    status;
    duration;
    serialize(ctx) {
      this.payload = import_shared.Bytes.concat([
        [
          (this.moreUpdatesFollow ? 128 : 0) | (this.requestWakeUpOnDemand ? 64 : 0) | this.sessionId & 63,
          this.status
        ]
      ]);
      if (this.duration) {
        this.payload = import_shared.Bytes.concat([
          this.payload,
          [this.duration.serializeReport()]
        ]);
      }
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      const message = {
        "session id": this.sessionId,
        "more updates follow": this.moreUpdatesFollow,
        status: (0, import_shared.getEnumMemberName)(import_core.SupervisionStatus, this.status)
      };
      if (this.duration) {
        message.duration = this.duration.toString();
      }
      return {
        ...super.toLogEntry(ctx),
        message
      };
    }
    toSupervisionResult() {
      if (this.status === import_core.SupervisionStatus.Working) {
        return {
          status: this.status,
          remainingDuration: this.duration
        };
      } else {
        return {
          status: this.status
        };
      }
    }
  };
  return SupervisionCCReport2 = _classThis;
})();
function testResponseForSupervisionCCGet(sent, received) {
  return received.sessionId === sent.sessionId;
}
__name(testResponseForSupervisionCCGet, "testResponseForSupervisionCCGet");
let SupervisionCCGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.SupervisionCommand.Get), (0, import_CommandClassDecorators.expectedCCResponse)(SupervisionCCReport, testResponseForSupervisionCCGet)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = SupervisionCC;
  var SupervisionCCGet2 = class extends _classSuper {
    static {
      __name(this, "SupervisionCCGet");
    }
    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);
      SupervisionCCGet2 = _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.sessionId = options.sessionId;
      this.requestStatusUpdates = options.requestStatusUpdates;
      this.encapsulated = options.encapsulated;
      this.encapsulated.endpointIndex = this.endpointIndex;
      this.encapsulated.encapsulatingCC = this;
    }
    static async from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 3);
      const requestStatusUpdates = !!(raw.payload[0] & 128);
      const sessionId = raw.payload[0] & 63;
      const encapsulated = await import_CommandClass.CommandClass.parse(raw.payload.subarray(2), ctx);
      return new this({
        nodeId: ctx.sourceNodeId,
        requestStatusUpdates,
        sessionId,
        encapsulated
      });
    }
    requestStatusUpdates;
    sessionId;
    encapsulated;
    async serialize(ctx) {
      const encapCC = await this.encapsulated.serialize(ctx);
      this.payload = import_shared.Bytes.concat([
        [
          (this.requestStatusUpdates ? 128 : 0) | this.sessionId & 63,
          encapCC.length
        ],
        encapCC
      ]);
      return super.serialize(ctx);
    }
    computeEncapsulationOverhead() {
      return super.computeEncapsulationOverhead() + 2;
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "session id": this.sessionId,
          "request updates": this.requestStatusUpdates
        }
      };
    }
  };
  return SupervisionCCGet2 = _classThis;
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SupervisionCC,
  SupervisionCCAPI,
  SupervisionCCGet,
  SupervisionCCReport,
  SupervisionCCValues
});
//# sourceMappingURL=SupervisionCC.js.map
