"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 __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 __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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var NotificationCC_exports = {};
__export(NotificationCC_exports, {
  NotificationCC: () => NotificationCC,
  NotificationCCAPI: () => NotificationCCAPI,
  NotificationCCEventSupportedGet: () => NotificationCCEventSupportedGet,
  NotificationCCEventSupportedReport: () => NotificationCCEventSupportedReport,
  NotificationCCGet: () => NotificationCCGet,
  NotificationCCReport: () => NotificationCCReport,
  NotificationCCSet: () => NotificationCCSet,
  NotificationCCSupportedGet: () => NotificationCCSupportedGet,
  NotificationCCSupportedReport: () => NotificationCCSupportedReport,
  NotificationCCValues: () => import_CCValues_generated.NotificationCCValues,
  getNotificationEnumBehavior: () => getNotificationEnumBehavior,
  getNotificationStateValueWithEnum: () => getNotificationStateValueWithEnum,
  getNotificationValueMetadata: () => getNotificationValueMetadata,
  shouldAutoCreateSyntheticDoorSensorValue: () => shouldAutoCreateSyntheticDoorSensorValue
});
module.exports = __toCommonJS(NotificationCC_exports);
var import_tslib = require("tslib");
var __validateArgs = __toESM(require("./NotificationCC._validateArgs.js"), 1);
var import_core = require("@zwave-js/core");
var import_shared = require("@zwave-js/shared");
var import_typeguards = require("alcalzone-shared/typeguards");
var import_API = require("../lib/API.js");
var import_CommandClass = require("../lib/CommandClass.js");
var import_CommandClassDecorators = require("../lib/CommandClassDecorators.js");
var import_NotificationEventPayload = require("../lib/NotificationEventPayload.js");
var import_Types = require("../lib/_Types.js");
var ccUtils = __toESM(require("../lib/utils.js"), 1);
var import_ApplicationStatusCC = require("./ApplicationStatusCC.js");
var import_AssociationGroupInfoCC = require("./AssociationGroupInfoCC.js");
var import_CCValues_generated = require("./_CCValues.generated.js");
const { validateArgs_NotificationCCAPI_sendReport, validateArgs_NotificationCCAPI_get, validateArgs_NotificationCCAPI_set, validateArgs_NotificationCCAPI_getSupportedEvents } = __validateArgs;
function shouldAutoCreateSyntheticDoorSensorValue(ctx, endpoint) {
  const valueDB = ctx.tryGetValueDB(endpoint.nodeId);
  if (!valueDB)
    return false;
  const supportedACEvents = valueDB.getValue(import_CCValues_generated.NotificationCCValues.supportedNotificationEvents(
    // Access Control
    6
  ).endpoint(endpoint.index));
  if (!supportedACEvents)
    return false;
  return supportedACEvents.includes(
    // Window/door is open
    22
  ) && supportedACEvents.includes(
    // Window/door is closed
    23
  );
}
__name(shouldAutoCreateSyntheticDoorSensorValue, "shouldAutoCreateSyntheticDoorSensorValue");
let NotificationCCAPI = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.API)(import_core.CommandClasses.Notification)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_API.PhysicalCCAPI;
  let _instanceExtraInitializers = [];
  let _sendReport_decorators;
  let _get_decorators;
  let _set_decorators;
  let _getSupportedEvents_decorators;
  var NotificationCCAPI2 = class extends _classSuper {
    static {
      __name(this, "NotificationCCAPI");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      _sendReport_decorators = [validateArgs_NotificationCCAPI_sendReport()];
      _get_decorators = [validateArgs_NotificationCCAPI_get()];
      _set_decorators = [validateArgs_NotificationCCAPI_set()];
      _getSupportedEvents_decorators = [validateArgs_NotificationCCAPI_getSupportedEvents()];
      (0, import_tslib.__esDecorate)(this, null, _sendReport_decorators, { kind: "method", name: "sendReport", static: false, private: false, access: { has: /* @__PURE__ */ __name((obj) => "sendReport" in obj, "has"), get: /* @__PURE__ */ __name((obj) => obj.sendReport, "get") }, metadata: _metadata }, null, _instanceExtraInitializers);
      (0, import_tslib.__esDecorate)(this, null, _get_decorators, { kind: "method", name: "get", static: false, private: false, access: { has: /* @__PURE__ */ __name((obj) => "get" in obj, "has"), get: /* @__PURE__ */ __name((obj) => obj.get, "get") }, metadata: _metadata }, null, _instanceExtraInitializers);
      (0, import_tslib.__esDecorate)(this, null, _set_decorators, { kind: "method", name: "set", static: false, private: false, access: { has: /* @__PURE__ */ __name((obj) => "set" in obj, "has"), get: /* @__PURE__ */ __name((obj) => obj.set, "get") }, metadata: _metadata }, null, _instanceExtraInitializers);
      (0, import_tslib.__esDecorate)(this, null, _getSupportedEvents_decorators, { kind: "method", name: "getSupportedEvents", static: false, private: false, access: { has: /* @__PURE__ */ __name((obj) => "getSupportedEvents" in obj, "has"), get: /* @__PURE__ */ __name((obj) => obj.getSupportedEvents, "get") }, metadata: _metadata }, null, _instanceExtraInitializers);
      (0, import_tslib.__esDecorate)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      NotificationCCAPI2 = _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.NotificationCommand.Report:
        case import_Types.NotificationCommand.Get:
          return true;
        // These exist starting with V1
        case import_Types.NotificationCommand.Set:
        case import_Types.NotificationCommand.SupportedGet:
          return this.version >= 2;
        case import_Types.NotificationCommand.EventSupportedGet:
          return this.version >= 3;
      }
      return super.supportsCommand(cmd);
    }
    get [import_API.POLL_VALUE]() {
      return async function({ property, propertyKey }) {
        const valueId = {
          commandClass: this.ccId,
          endpoint: this.endpoint.index,
          property,
          propertyKey
        };
        if (import_CCValues_generated.NotificationCCValues.notificationVariable.is(valueId)) {
          const notificationType = this.tryGetValueDB()?.getMetadata(valueId)?.ccSpecific?.notificationType;
          if (notificationType != void 0) {
            return this.getInternal({ notificationType });
          }
        }
        (0, import_API.throwUnsupportedProperty)(this.ccId, property);
      };
    }
    /**
     * @internal
     */
    async getInternal(options) {
      this.assertSupportsCommand(import_Types.NotificationCommand, import_Types.NotificationCommand.Get);
      const cc = new NotificationCCGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        ...options
      });
      return this.host.sendCommand(cc, this.commandOptions);
    }
    async sendReport(options) {
      this.assertSupportsCommand(import_Types.NotificationCommand, import_Types.NotificationCommand.Report);
      const cc = new NotificationCCReport({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        ...options
      });
      return this.host.sendCommand(cc, this.commandOptions);
    }
    async get(options) {
      const response = await this.getInternal(options);
      if (response) {
        return (0, import_shared.pick)(response, [
          "notificationStatus",
          "notificationEvent",
          "alarmLevel",
          "eventParameters",
          "sequenceNumber"
        ]);
      }
    }
    async set(notificationType, notificationStatus) {
      this.assertSupportsCommand(import_Types.NotificationCommand, import_Types.NotificationCommand.Set);
      const cc = new NotificationCCSet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        notificationType,
        notificationStatus
      });
      return this.host.sendCommand(cc, this.commandOptions);
    }
    // oxlint-disable-next-line typescript/explicit-module-boundary-types
    async getSupported() {
      this.assertSupportsCommand(import_Types.NotificationCommand, import_Types.NotificationCommand.SupportedGet);
      const cc = new NotificationCCSupportedGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      if (response) {
        return (0, import_shared.pick)(response, [
          "supportsV1Alarm",
          "supportedNotificationTypes"
        ]);
      }
    }
    async getSupportedEvents(notificationType) {
      this.assertSupportsCommand(import_Types.NotificationCommand, import_Types.NotificationCommand.EventSupportedGet);
      const cc = new NotificationCCEventSupportedGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        notificationType
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      return response?.supportedEvents;
    }
    constructor() {
      super(...arguments);
      (0, import_tslib.__runInitializers)(this, _instanceExtraInitializers);
    }
  };
  return NotificationCCAPI2 = _classThis;
})();
function getNotificationEnumBehavior(notification, valueConfig) {
  const variable = notification.variables.find((v) => v.states.has(valueConfig.value));
  if (!variable)
    return "none";
  const numStatesWithEnums = [...variable.states.values()].filter((val) => val.parameter?.type === "enum").length;
  if (numStatesWithEnums === 0)
    return "none";
  if (numStatesWithEnums === 1 && variable.states.size === 1) {
    return "replace";
  }
  return "extend";
}
__name(getNotificationEnumBehavior, "getNotificationEnumBehavior");
function getNotificationStateValueWithEnum(stateValue, enumValue) {
  return stateValue << 8 | enumValue;
}
__name(getNotificationStateValueWithEnum, "getNotificationStateValueWithEnum");
function getNotificationValueMetadata(previous, notification, valueConfig) {
  const metadata = previous ?? {
    ...import_core.ValueMetadata.ReadOnlyUInt8,
    label: valueConfig.variableName,
    states: {},
    ccSpecific: {
      notificationType: notification.type
    }
  };
  if (valueConfig.idle) {
    metadata.states[0] = "idle";
  }
  const enumBehavior = getNotificationEnumBehavior(notification, valueConfig);
  if (enumBehavior !== "replace") {
    metadata.states[valueConfig.value] = valueConfig.label;
  }
  if (valueConfig.parameter?.type === "enum") {
    for (const [key, label] of Object.entries(valueConfig.parameter.values)) {
      const value = parseInt(key);
      const stateKey = enumBehavior === "replace" ? value : getNotificationStateValueWithEnum(valueConfig.value, value);
      metadata.states[stateKey] = label;
    }
  }
  return metadata;
}
__name(getNotificationValueMetadata, "getNotificationValueMetadata");
let NotificationCC = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.commandClass)(import_core.CommandClasses.Notification), (0, import_CommandClassDecorators.implementedVersion)(8), (0, import_CommandClassDecorators.ccValues)(import_CCValues_generated.NotificationCCValues)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_CommandClass.CommandClass;
  var NotificationCC2 = class extends _classSuper {
    static {
      __name(this, "NotificationCC");
    }
    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);
      NotificationCC2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    // former AlarmCC (v1..v2)
    determineRequiredCCInterviews() {
      return [
        ...super.determineRequiredCCInterviews(),
        import_core.CommandClasses.Association,
        import_core.CommandClasses["Multi Channel Association"],
        import_core.CommandClasses["Association Group Information"]
      ];
    }
    async determineNotificationMode(ctx, api, supportedNotificationEvents) {
      const node = this.getNode(ctx);
      if (!node.supportsCC(import_core.CommandClasses.Association))
        return "pull";
      if (node.supportsCC(import_core.CommandClasses["Association Group Information"])) {
        try {
          const groupsIssueingNotifications = import_AssociationGroupInfoCC.AssociationGroupInfoCC.findGroupsForIssuedCommand(ctx, node, this.ccId, import_Types.NotificationCommand.Report);
          return groupsIssueingNotifications.length > 0 ? "push" : "pull";
        } catch {
        }
      }
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: `determining whether this node is pull or push...`,
        direction: "outbound"
      });
      for (const [type, events] of supportedNotificationEvents) {
        if (events.length === 0)
          continue;
        await api.set(type, true);
        try {
          const resp = await api.get({
            notificationType: type,
            notificationEvent: events[0]
          });
          switch (resp?.notificationStatus) {
            case 255:
              return "push";
            case 254:
            case 0:
              return "pull";
          }
        } catch {
        }
      }
      return "push";
    }
    /** Whether the node implements push or pull notifications */
    static getNotificationMode(ctx, node) {
      return ctx.getValueDB(node.id).getValue(import_CCValues_generated.NotificationCCValues.notificationMode.id);
    }
    /** Returns the supported notification events for a given notification type */
    static getSupportedNotificationEvents(ctx, node, type) {
      return ctx.getValueDB(node.id).getValue(import_CCValues_generated.NotificationCCValues.supportedNotificationEvents(type).id);
    }
    async interview(ctx) {
      const node = this.getNode(ctx);
      const endpoint = this.getEndpoint(ctx);
      const api = import_API.CCAPI.create(import_core.CommandClasses.Notification, ctx, endpoint).withOptions({
        priority: import_core.MessagePriority.NodeQuery
      });
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: `Interviewing ${this.ccName}...`,
        direction: "none"
      });
      try {
        await ccUtils.assignLifelineIssueingCommand(ctx, endpoint, this.ccId, import_Types.NotificationCommand.Report);
      } catch {
        ctx.logNode(node.id, {
          endpoint: endpoint.index,
          message: `Configuring associations to receive ${(0, import_core.getCCName)(this.ccId)} reports failed!`,
          level: "warn"
        });
      }
      let supportsV1Alarm = false;
      if (api.version >= 2) {
        ctx.logNode(node.id, {
          endpoint: this.endpointIndex,
          message: "querying supported notification types...",
          direction: "outbound"
        });
        const suppResponse = await api.getSupported();
        if (!suppResponse) {
          ctx.logNode(node.id, {
            endpoint: this.endpointIndex,
            message: "Querying supported notification types timed out, skipping interview...",
            level: "warn"
          });
          return;
        }
        supportsV1Alarm = suppResponse.supportsV1Alarm;
        const supportedNotificationTypes = suppResponse.supportedNotificationTypes;
        const supportedNotificationNames = supportedNotificationTypes.map(import_core.getNotificationName);
        const supportedNotificationEvents = /* @__PURE__ */ new Map();
        const logMessage = `received supported notification types:${supportedNotificationNames.map((name) => `
\xB7 ${name}`).join("")}`;
        ctx.logNode(node.id, {
          endpoint: this.endpointIndex,
          message: logMessage,
          direction: "inbound"
        });
        if (api.version >= 3) {
          for (let i = 0; i < supportedNotificationTypes.length; i++) {
            const type = supportedNotificationTypes[i];
            const name = supportedNotificationNames[i];
            ctx.logNode(node.id, {
              endpoint: this.endpointIndex,
              message: `querying supported notification events for ${name}...`,
              direction: "outbound"
            });
            const supportedEvents = await api.getSupportedEvents(type);
            if (supportedEvents) {
              supportedNotificationEvents.set(type, supportedEvents);
              ctx.logNode(node.id, {
                endpoint: this.endpointIndex,
                message: `received supported notification events for ${name}: ${supportedEvents.map(String).join(", ")}`,
                direction: "inbound"
              });
            }
          }
        }
        let notificationMode = this.getValue(ctx, import_CCValues_generated.NotificationCCValues.notificationMode);
        if (notificationMode !== "push" && notificationMode !== "pull") {
          notificationMode = await this.determineNotificationMode(ctx, api, supportedNotificationEvents);
          this.setValue(ctx, import_CCValues_generated.NotificationCCValues.notificationMode, notificationMode);
        }
        if (notificationMode === "pull") {
          await this.refreshValues(ctx);
        } else {
          await this.refreshValues(ctx);
          for (let i = 0; i < supportedNotificationTypes.length; i++) {
            const type = supportedNotificationTypes[i];
            const name = supportedNotificationNames[i];
            ctx.logNode(node.id, {
              endpoint: this.endpointIndex,
              message: `enabling notifications for ${name}...`,
              direction: "outbound"
            });
            await api.set(type, true);
          }
        }
      }
      if (api.version === 1 || supportsV1Alarm) {
        this.ensureMetadata(ctx, import_CCValues_generated.NotificationCCValues.alarmType);
        this.ensureMetadata(ctx, import_CCValues_generated.NotificationCCValues.alarmLevel);
      }
      this.applyAlarmMappingCompat(ctx);
      this.applyNotificationRemappings(ctx);
      this.initNotificationIdleValues(ctx);
      this.setInterviewComplete(ctx, true);
    }
    /**
     * Applies the `alarmMapping` compat flag by adding metadata and supported notification
     * types/events for the alarm mapping targets.
     */
    applyAlarmMappingCompat(ctx) {
      const mappings = ctx.getDeviceConfig?.(this.nodeId)?.compat?.alarmMapping;
      if (!mappings)
        return;
      const node = this.getNode(ctx);
      const supportedNotifications = /* @__PURE__ */ new Map();
      for (const type of this.getValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationTypes) ?? []) {
        supportedNotifications.set(type, new Set(NotificationCC2.getSupportedNotificationEvents(ctx, node, type) ?? []));
      }
      for (const { to } of mappings) {
        const notification = (0, import_core.getNotification)(to.notificationType);
        if (!notification)
          continue;
        const valueConfig = (0, import_core.getNotificationValue)(notification, to.notificationEvent);
        if (!supportedNotifications.has(to.notificationType)) {
          supportedNotifications.set(to.notificationType, /* @__PURE__ */ new Set());
        }
        const supportedNotificationTypesSet = supportedNotifications.get(to.notificationType);
        supportedNotificationTypesSet.add(to.notificationEvent);
        if (valueConfig?.type !== "state")
          continue;
        const notificationValue = import_CCValues_generated.NotificationCCValues.notificationVariable(notification.name, valueConfig.variableName);
        const metadata = getNotificationValueMetadata(this.getMetadata(ctx, notificationValue), notification, valueConfig);
        this.setMetadata(ctx, notificationValue, metadata);
      }
      this.setValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationTypes, [...supportedNotifications.keys()]);
      for (const [type, events] of supportedNotifications) {
        this.setValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationEvents(type), [...events]);
      }
    }
    /**
     * Applies the `remapNotifications` compat flag by modifying the supported notification
     * types/events in cache and creating metadata for remapping targets.
     */
    applyNotificationRemappings(ctx) {
      const remappings = ctx.getDeviceConfig?.(this.nodeId)?.compat?.remapNotifications;
      if (!remappings?.length)
        return;
      ctx.logNode(this.nodeId, {
        message: `Applying notification remapping compat flag...`,
        direction: "none",
        level: "verbose"
      });
      const supportedTypes = new Set(this.getValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationTypes) ?? []);
      const supportedEvents = /* @__PURE__ */ new Map();
      for (const type of supportedTypes) {
        const events = NotificationCC2.getSupportedNotificationEvents(ctx, this.getNode(ctx), type);
        if (events) {
          supportedEvents.set(type, new Set(events));
        }
      }
      for (const mapping of remappings) {
        const fromEvents = supportedEvents.get(mapping.from.notificationType);
        if (fromEvents) {
          fromEvents.delete(mapping.from.notificationEvent);
          if (fromEvents.size === 0) {
            supportedEvents.delete(mapping.from.notificationType);
            supportedTypes.delete(mapping.from.notificationType);
          }
        }
        if (mapping.action.type === "remap") {
          const to = mapping.action.to;
          supportedTypes.add(to.notificationType);
          if (!supportedEvents.has(to.notificationType)) {
            supportedEvents.set(to.notificationType, /* @__PURE__ */ new Set());
          }
          supportedEvents.get(to.notificationType).add(to.notificationEvent);
        }
      }
      this.setValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationTypes, [...supportedTypes]);
      for (const [type, events] of supportedEvents) {
        this.setValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationEvents(type), [...events]);
      }
      for (const [type, events] of supportedEvents) {
        const notification = (0, import_core.getNotification)(type);
        if (!notification)
          continue;
        let isFirst = true;
        for (const value of events) {
          const valueConfig = (0, import_core.getNotificationValue)(notification, value);
          if (valueConfig?.type !== "state")
            continue;
          const notificationValue = import_CCValues_generated.NotificationCCValues.notificationVariable(notification.name, valueConfig.variableName);
          const metadata = getNotificationValueMetadata(isFirst ? void 0 : this.getMetadata(ctx, notificationValue), notification, valueConfig);
          this.setMetadata(ctx, notificationValue, metadata);
          isFirst = false;
        }
      }
    }
    /**
     * Sets idle values for all supported notification variables that have an idle state
     * and don't have a value yet.
     */
    initNotificationIdleValues(ctx) {
      const supportedTypes = this.getValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationTypes) ?? [];
      for (const type of supportedTypes) {
        const notification = (0, import_core.getNotification)(type);
        if (!notification)
          continue;
        const events = NotificationCC2.getSupportedNotificationEvents(ctx, this.getNode(ctx), type);
        if (!events)
          continue;
        for (const variable of notification.variables.filter((v) => !!v.idle)) {
          if ([...variable.states.keys()].some((key) => events.includes(key))) {
            const value = import_CCValues_generated.NotificationCCValues.notificationVariable(notification.name, variable.name);
            if (this.getValue(ctx, value) == void 0) {
              this.setValue(ctx, value, 0);
            }
          }
        }
      }
    }
    async refreshValues(ctx, options) {
      const node = this.getNode(ctx);
      const endpoint = this.getEndpoint(ctx);
      const api = import_API.CCAPI.create(import_core.CommandClasses.Notification, ctx, endpoint).withOptions({
        priority: options?.priority ?? import_core.MessagePriority.NodeQuery
      });
      const supportedNotificationTypes = this.getValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationTypes) ?? [];
      const supportedNotificationNames = supportedNotificationTypes.map(import_core.getNotificationName);
      for (let i = 0; i < supportedNotificationTypes.length; i++) {
        const type = supportedNotificationTypes[i];
        const name = supportedNotificationNames[i];
        ctx.logNode(node.id, {
          endpoint: this.endpointIndex,
          message: `querying notification status for ${name}...`,
          direction: "outbound"
        });
        const response = await api.getInternal({
          notificationType: type
        });
        if (response) {
          await node.handleCommand(response);
        }
      }
      this.setValue(ctx, import_CCValues_generated.NotificationCCValues.lastRefresh, Date.now());
    }
    shouldRefreshValues(ctx) {
      const isPullMode = NotificationCC2.getNotificationMode(ctx, this.getNode(ctx)) === "pull";
      if (!isPullMode)
        return false;
      const lastUpdated = this.getValue(ctx, import_CCValues_generated.NotificationCCValues.lastRefresh);
      return lastUpdated == void 0 || Date.now() - lastUpdated > import_core.timespan.hours(6);
    }
  };
  return NotificationCC2 = _classThis;
})();
function getCCResponseForNotificationCCSet(ctx, sent) {
  if (sent.isSinglecast() && !sent.notificationStatus && !sent.isEncapsulatedWith(import_core.CommandClasses.Supervision) && ctx.getNode(sent.nodeId)?.supportsCC(import_core.CommandClasses["Application Status"])) {
    return import_ApplicationStatusCC.ApplicationStatusCCRejectedRequest;
  }
}
__name(getCCResponseForNotificationCCSet, "getCCResponseForNotificationCCSet");
let NotificationCCSet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.NotificationCommand.Set), (0, import_CommandClassDecorators.expectedCCResponse)(getCCResponseForNotificationCCSet), (0, import_CommandClassDecorators.useSupervision)()];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = NotificationCC;
  var NotificationCCSet2 = class extends _classSuper {
    static {
      __name(this, "NotificationCCSet");
    }
    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);
      NotificationCCSet2 = _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.notificationType = options.notificationType;
      this.notificationStatus = options.notificationStatus;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 2);
      const notificationType = raw.payload[0];
      const notificationStatus = raw.payload[1] === 255;
      return new this({
        nodeId: ctx.sourceNodeId,
        notificationType,
        notificationStatus
      });
    }
    notificationType;
    notificationStatus;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([
        this.notificationType,
        this.notificationStatus ? 255 : 0
      ]);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "notification type": (0, import_core.getNotificationName)(this.notificationType),
          status: this.notificationStatus
        }
      };
    }
  };
  return NotificationCCSet2 = _classThis;
})();
let NotificationCCReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.NotificationCommand.Report), (0, import_CommandClassDecorators.useSupervision)()];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = NotificationCC;
  var NotificationCCReport2 = class extends _classSuper {
    static {
      __name(this, "NotificationCCReport");
    }
    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);
      NotificationCCReport2 = _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 (options.alarmType != void 0) {
        this.alarmType = options.alarmType;
        this.alarmLevel = options.alarmLevel;
      }
      if (options.notificationType != void 0) {
        this.notificationType = options.notificationType;
        this.notificationStatus = options.notificationStatus ?? true;
        this.notificationEvent = options.notificationEvent;
        this.eventParameters = options.eventParameters;
        this.sequenceNumber = options.sequenceNumber;
      }
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 2);
      const alarmType = raw.payload[0];
      const alarmLevel = raw.payload[1];
      if (raw.payload.length < 7) {
        return new this({
          nodeId: ctx.sourceNodeId,
          alarmType,
          alarmLevel
        });
      }
      const notificationStatus = raw.payload[3];
      const notificationType = raw.payload[4];
      const notificationEvent = raw.payload[5];
      const containsSeqNum = !!(raw.payload[6] & 128);
      const numEventParams = raw.payload[6] & 31;
      let eventParameters;
      if (numEventParams > 0) {
        (0, import_core.validatePayload)(raw.payload.length >= 7 + numEventParams);
        eventParameters = raw.payload.subarray(7, 7 + numEventParams);
      }
      let sequenceNumber;
      if (containsSeqNum) {
        (0, import_core.validatePayload)(raw.payload.length >= 7 + numEventParams + 1);
        sequenceNumber = raw.payload[7 + numEventParams];
      }
      return new this({
        nodeId: ctx.sourceNodeId,
        alarmType,
        alarmLevel,
        notificationStatus,
        notificationType,
        notificationEvent,
        eventParameters,
        sequenceNumber
      });
    }
    persistValues(ctx) {
      if (!super.persistValues(ctx))
        return false;
      const ccVersion = (0, import_CommandClass.getEffectiveCCVersion)(ctx, this);
      if (this.alarmType != void 0 && this.alarmLevel != void 0 && this.alarmType !== 0) {
        if (ccVersion >= 2) {
          const supportedNotificationTypes = this.getValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationTypes);
          if ((0, import_typeguards.isArray)(supportedNotificationTypes) && supportedNotificationTypes.includes(this.alarmType)) {
            const supportedNotificationEvents = NotificationCC.getSupportedNotificationEvents(ctx, this.getNode(ctx), this.alarmType);
            if ((0, import_typeguards.isArray)(supportedNotificationEvents) && supportedNotificationEvents.includes(this.alarmLevel)) {
              ctx.logNode(this.nodeId, `treating V1 Alarm frame as Notification Report`);
              this.notificationType = this.alarmType;
              this.notificationEvent = this.alarmLevel;
              this.alarmType = void 0;
              this.alarmLevel = void 0;
            }
          }
        } else {
          const mapping = ctx.getDeviceConfig?.(this.nodeId)?.compat?.alarmMapping;
          const match = mapping?.find((m) => m.from.alarmType === this.alarmType && (m.from.alarmLevel == void 0 || m.from.alarmLevel === this.alarmLevel));
          if (match) {
            ctx.logNode(this.nodeId, `compat mapping found, treating V1 Alarm frame as Notification Report`);
            this.notificationType = match.to.notificationType;
            this.notificationEvent = match.to.notificationEvent;
            if (match.to.eventParameters) {
              this.eventParameters = {};
              for (const [key, val] of Object.entries(match.to.eventParameters)) {
                if (typeof val === "number") {
                  this.eventParameters[key] = val;
                } else if (val === "alarmLevel") {
                  this.eventParameters[key] = this.alarmLevel;
                }
              }
            }
          }
        }
      }
      this.parseEventParameters(ctx);
      if (this.alarmType != void 0) {
        const alarmTypeValue = import_CCValues_generated.NotificationCCValues.alarmType;
        this.ensureMetadata(ctx, alarmTypeValue);
        this.setValue(ctx, alarmTypeValue, this.alarmType);
      }
      if (this.alarmLevel != void 0) {
        const alarmLevelValue = import_CCValues_generated.NotificationCCValues.alarmLevel;
        this.ensureMetadata(ctx, alarmLevelValue);
        this.setValue(ctx, alarmLevelValue, this.alarmLevel);
      }
      return true;
    }
    alarmType;
    alarmLevel;
    notificationType;
    notificationStatus;
    notificationEvent;
    eventParameters;
    sequenceNumber;
    toLogEntry(ctx) {
      let message = {};
      if (this.alarmType) {
        message = {
          "V1 alarm type": this.alarmType,
          "V1 alarm level": this.alarmLevel
        };
      }
      let valueConfig;
      if (this.notificationType) {
        const notification = (0, import_core.getNotification)(this.notificationType);
        if (notification) {
          valueConfig = (0, import_core.getNotificationValue)(notification, this.notificationEvent);
        }
        if (valueConfig) {
          message = {
            ...message,
            "notification type": (0, import_core.getNotificationName)(this.notificationType),
            "notification status": this.notificationStatus,
            [`notification ${valueConfig.type}`]: valueConfig.label ?? `Unknown (${(0, import_shared.num2hex)(this.notificationEvent)})`
          };
        } else if (this.notificationEvent === 0) {
          message = {
            ...message,
            "notification type": this.notificationType,
            "notification status": this.notificationStatus,
            "notification state": "idle"
          };
        } else {
          message = {
            ...message,
            "notification type": this.notificationType,
            "notification status": this.notificationStatus,
            "notification event": (0, import_shared.num2hex)(this.notificationEvent)
          };
        }
      }
      if (this.sequenceNumber != void 0) {
        message["sequence number"] = this.sequenceNumber;
      }
      if (this.eventParameters != void 0) {
        if (typeof this.eventParameters === "number") {
          let found = false;
          if (valueConfig?.parameter?.type === "enum") {
            const label = valueConfig.parameter.values[this.eventParameters];
            if (label) {
              message["state parameters"] = label;
              found = true;
            }
          }
          if (!found) {
            message["state parameters"] = (0, import_shared.num2hex)(this.eventParameters);
          }
        } else if ((0, import_shared.isUint8Array)(this.eventParameters)) {
          message["event parameters"] = (0, import_shared.buffer2hex)(this.eventParameters);
        } else if (this.eventParameters instanceof import_core.Duration) {
          message["event parameters"] = this.eventParameters.toString();
        } else {
          message["event parameters"] = Object.entries(this.eventParameters).map(([param, val]) => `
  ${param}: ${(0, import_shared.num2hex)(val)}`).join("");
        }
      } else if (valueConfig?.parameter?.type === "enum" && valueConfig.parameter.default != void 0) {
        const label = valueConfig.parameter.values[valueConfig.parameter.default];
        if (label) {
          message["state parameters"] = `${label} (omitted)`;
        }
      }
      return {
        ...super.toLogEntry(ctx),
        message
      };
    }
    parseEventParameters(ctx) {
      if (this.notificationType == void 0 || this.notificationEvent == void 0) {
        return;
      }
      const notification = (0, import_core.getNotification)(this.notificationType);
      if (!notification)
        return;
      const valueConfig = (0, import_core.getNotificationValue)(notification, this.notificationEvent);
      if (!valueConfig)
        return;
      if (valueConfig.parameter?.type === "duration") {
        if (!(0, import_shared.isUint8Array)(this.eventParameters)) {
          return;
        }
        this.eventParameters = import_core.Duration.parseReport(this.eventParameters[0]);
      } else if (valueConfig.parameter?.type === "commandclass") {
        if (!(0, import_shared.isUint8Array)(this.eventParameters)) {
          return;
        }
        if (this.eventParameters.length === 1 && notification.type === 6 && (this.notificationEvent === 5 || this.notificationEvent === 6)) {
          this.eventParameters = {
            userId: this.eventParameters[0]
          };
        } else {
          try {
            const raw = import_CommandClass.CCRaw.parse(this.eventParameters);
            if (raw.ccCommand == void 0) {
              import_core.validatePayload.fail("event parameters contain an invalid CC");
            }
            const CommandConstructor = (0, import_CommandClassDecorators.getCCCommandConstructor)(raw.ccId, raw.ccCommand);
            if (!CommandConstructor) {
              import_core.validatePayload.fail("event parameters contain an invalid CC");
            }
            const cc = CommandConstructor.from(raw, {
              ...ctx,
              frameType: "singlecast",
              sourceNodeId: this.nodeId,
              // Security encapsulation is handled outside of this CC,
              // so it is not needed here:
              hasSecurityClass: /* @__PURE__ */ __name(() => false, "hasSecurityClass"),
              getHighestSecurityClass: /* @__PURE__ */ __name(() => import_core.SecurityClass.None, "getHighestSecurityClass"),
              setSecurityClass: /* @__PURE__ */ __name(() => {
              }, "setSecurityClass"),
              securityManager: void 0,
              securityManager2: void 0,
              securityManagerLR: void 0
            });
            if (cc instanceof Promise) {
              import_core.validatePayload.fail("Cannot asynchronously parse CC from event parameters");
            }
            (0, import_core.validatePayload)(!(cc instanceof import_CommandClass.InvalidCC));
            cc.encapsulatingCC = this;
            if ((0, import_NotificationEventPayload.isNotificationEventPayload)(cc)) {
              this.eventParameters = cc.toNotificationEventParameters();
            } else {
              let json = cc.toJSON();
              if ("nodeId" in json && "ccId" in json && "payload" in json) {
                json = (0, import_shared.pick)(json, ["payload"]);
              }
              this.eventParameters = json;
            }
          } catch (e) {
            if ((0, import_core.isZWaveError)(e) && e.code === import_core.ZWaveErrorCodes.PacketFormat_InvalidPayload && (0, import_shared.isUint8Array)(this.eventParameters)) {
              const { ccId, ccCommand } = import_CommandClass.CCRaw.parse(this.eventParameters);
              if (ccId === import_core.CommandClasses["User Code"] && ccCommand === import_Types.UserCodeCommand.Report && this.eventParameters.length >= 3) {
                this.eventParameters = {
                  userId: this.eventParameters[2]
                };
              } else {
                ctx.logNode(this.nodeId, `Failed to parse Notification CC event parameters, ignoring them...`, "error");
              }
            } else {
              throw e;
            }
          }
        }
      } else if (valueConfig.parameter?.type === "value") {
        if (!(0, import_shared.isUint8Array)(this.eventParameters)) {
          return;
        }
        this.eventParameters = {
          [valueConfig.parameter.propertyName]: import_shared.Bytes.view(this.eventParameters).readUIntBE(0, this.eventParameters.length)
        };
      } else if (valueConfig.parameter?.type === "enum") {
        this.eventParameters = (0, import_shared.isUint8Array)(this.eventParameters) && this.eventParameters.length === 1 ? this.eventParameters[0] : void 0;
        if (this.eventParameters == void 0 && valueConfig.parameter.default != void 0) {
          this.eventParameters = valueConfig.parameter.default;
        }
      }
    }
    serialize(ctx) {
      if (this.notificationType != void 0) {
        if (this.notificationEvent == void 0) {
          throw new import_core.ZWaveError(`Notification CC reports requires the notification event to be set!`, import_core.ZWaveErrorCodes.Argument_Invalid);
        } else if (this.eventParameters != void 0 && !(0, import_shared.isUint8Array)(this.eventParameters)) {
          throw new import_core.ZWaveError(`When sending Notification CC reports, the event parameters can only be buffers!`, import_core.ZWaveErrorCodes.Argument_Invalid);
        }
        const controlByte = (this.sequenceNumber != void 0 ? 128 : 0) | (this.eventParameters?.length ?? 0) & 31;
        this.payload = import_shared.Bytes.from([
          0,
          0,
          0,
          255,
          this.notificationType,
          this.notificationEvent,
          controlByte
        ]);
        if (this.eventParameters) {
          this.payload = import_shared.Bytes.concat([
            this.payload,
            this.eventParameters
          ]);
        }
        if (this.sequenceNumber != void 0) {
          this.payload = import_shared.Bytes.concat([
            this.payload,
            [this.sequenceNumber]
          ]);
        }
      } else {
        this.payload = import_shared.Bytes.from([
          this.alarmType ?? 0,
          this.alarmLevel ?? 0
        ]);
      }
      return super.serialize(ctx);
    }
  };
  return NotificationCCReport2 = _classThis;
})();
let NotificationCCGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.NotificationCommand.Get), (0, import_CommandClassDecorators.expectedCCResponse)(NotificationCCReport)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = NotificationCC;
  var NotificationCCGet2 = class extends _classSuper {
    static {
      __name(this, "NotificationCCGet");
    }
    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);
      NotificationCCGet2 = _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 ("alarmType" in options) {
        this.alarmType = options.alarmType;
      } else {
        this.notificationType = options.notificationType;
        this.notificationEvent = options.notificationEvent;
      }
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 1);
      if (raw.payload.length >= 2) {
        const notificationType = raw.payload[1];
        let notificationEvent;
        if (raw.payload.length >= 3 && notificationType != 255) {
          notificationEvent = raw.payload[2];
        }
        return new this({
          nodeId: ctx.sourceNodeId,
          notificationType,
          notificationEvent
        });
      } else {
        const alarmType = raw.payload[0];
        return new this({
          nodeId: ctx.sourceNodeId,
          alarmType
        });
      }
    }
    /** Proprietary V1/V2 alarm type */
    alarmType;
    /** Regulated V3+ notification type */
    notificationType;
    notificationEvent;
    serialize(ctx) {
      const notificationEvent = this.notificationEvent === 255 ? 0 : this.notificationEvent;
      this.payload = import_shared.Bytes.from([
        this.alarmType ?? 0,
        this.notificationType ?? 255,
        notificationEvent ?? 0
      ]);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      const message = {};
      if (this.alarmType != void 0) {
        message["V1 alarm type"] = this.alarmType;
      }
      if (this.notificationType != void 0) {
        message["notification type"] = (0, import_core.getNotificationName)(this.notificationType);
        if (this.notificationEvent != void 0) {
          message["notification event"] = (0, import_core.getNotificationEventName)(this.notificationType, this.notificationEvent);
        }
      }
      return {
        ...super.toLogEntry(ctx),
        message
      };
    }
  };
  return NotificationCCGet2 = _classThis;
})();
let NotificationCCSupportedReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.NotificationCommand.SupportedReport), (0, import_CommandClassDecorators.ccValueProperty)("supportsV1Alarm", import_CCValues_generated.NotificationCCValues.supportsV1Alarm), (0, import_CommandClassDecorators.ccValueProperty)("supportedNotificationTypes", import_CCValues_generated.NotificationCCValues.supportedNotificationTypes)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = NotificationCC;
  var NotificationCCSupportedReport2 = class extends _classSuper {
    static {
      __name(this, "NotificationCCSupportedReport");
    }
    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);
      NotificationCCSupportedReport2 = _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.supportsV1Alarm = options.supportsV1Alarm;
      this.supportedNotificationTypes = options.supportedNotificationTypes;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 1);
      const supportsV1Alarm = !!(raw.payload[0] & 128);
      const numBitMaskBytes = raw.payload[0] & 31;
      (0, import_core.validatePayload)(numBitMaskBytes > 0, raw.payload.length >= 1 + numBitMaskBytes);
      const notificationBitMask = raw.payload.subarray(1, 1 + numBitMaskBytes);
      const supportedNotificationTypes = (0, import_core.parseBitMask)(
        notificationBitMask,
        // bit 0 is ignored, but counting still starts at 1, so the first bit must have the value 0
        0
      );
      return new this({
        nodeId: ctx.sourceNodeId,
        supportsV1Alarm,
        supportedNotificationTypes
      });
    }
    supportsV1Alarm;
    supportedNotificationTypes;
    serialize(ctx) {
      const bitMask = (0, import_core.encodeBitMask)(this.supportedNotificationTypes, Math.max(...this.supportedNotificationTypes), 0);
      this.payload = import_shared.Bytes.concat([
        [
          (this.supportsV1Alarm ? 128 : 0) | bitMask.length
        ],
        bitMask
      ]);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "supports V1 alarm": this.supportsV1Alarm,
          "supported notification types": this.supportedNotificationTypes.map((t) => `
\xB7 ${(0, import_core.getNotificationName)(t)}`).join("")
        }
      };
    }
  };
  return NotificationCCSupportedReport2 = _classThis;
})();
let NotificationCCSupportedGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.NotificationCommand.SupportedGet), (0, import_CommandClassDecorators.expectedCCResponse)(NotificationCCSupportedReport)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = NotificationCC;
  var NotificationCCSupportedGet2 = class extends _classSuper {
    static {
      __name(this, "NotificationCCSupportedGet");
    }
    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);
      NotificationCCSupportedGet2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
  };
  return NotificationCCSupportedGet2 = _classThis;
})();
let NotificationCCEventSupportedReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.NotificationCommand.EventSupportedReport)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = NotificationCC;
  var NotificationCCEventSupportedReport2 = class extends _classSuper {
    static {
      __name(this, "NotificationCCEventSupportedReport");
    }
    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);
      NotificationCCEventSupportedReport2 = _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.notificationType = options.notificationType;
      this.supportedEvents = options.supportedEvents;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 1);
      const notificationType = raw.payload[0];
      const numBitMaskBytes = raw.payload[1] & 31;
      if (numBitMaskBytes === 0) {
        return new this({
          nodeId: ctx.sourceNodeId,
          notificationType,
          supportedEvents: []
        });
      }
      (0, import_core.validatePayload)(raw.payload.length >= 2 + numBitMaskBytes);
      const eventBitMask = raw.payload.subarray(2, 2 + numBitMaskBytes);
      const supportedEvents = (0, import_core.parseBitMask)(
        eventBitMask,
        // In this mask, bit 0 is ignored, but counting still starts at 1, so the first bit must have the value 0
        0
      );
      return new this({
        nodeId: ctx.sourceNodeId,
        notificationType,
        supportedEvents
      });
    }
    persistValues(ctx) {
      if (!super.persistValues(ctx))
        return false;
      this.setValue(ctx, import_CCValues_generated.NotificationCCValues.supportedNotificationEvents(this.notificationType), this.supportedEvents);
      const notification = (0, import_core.getNotification)(this.notificationType);
      if (!notification) {
        this.setMetadata(ctx, import_CCValues_generated.NotificationCCValues.unknownNotificationType(this.notificationType));
      } else {
        let isFirst = true;
        for (const value of this.supportedEvents) {
          const valueConfig = (0, import_core.getNotificationValue)(notification, value);
          if (valueConfig?.type === "state") {
            const notificationValue = import_CCValues_generated.NotificationCCValues.notificationVariable(notification.name, valueConfig.variableName);
            const metadata = getNotificationValueMetadata(isFirst ? void 0 : this.getMetadata(ctx, notificationValue), notification, valueConfig);
            this.setMetadata(ctx, notificationValue, metadata);
            isFirst = false;
          }
        }
      }
      return true;
    }
    notificationType;
    supportedEvents;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([this.notificationType, 0]);
      if (this.supportedEvents.length > 0) {
        const bitMask = (0, import_core.encodeBitMask)(this.supportedEvents, Math.max(...this.supportedEvents), 0);
        this.payload[1] = bitMask.length;
        this.payload = import_shared.Bytes.concat([this.payload, bitMask]);
      }
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "notification type": (0, import_core.getNotificationName)(this.notificationType),
          "supported events": this.supportedEvents.map((e) => `
\xB7 ${(0, import_core.getNotificationValueName)(this.notificationType, e)}`).join("")
        }
      };
    }
  };
  return NotificationCCEventSupportedReport2 = _classThis;
})();
let NotificationCCEventSupportedGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.NotificationCommand.EventSupportedGet), (0, import_CommandClassDecorators.expectedCCResponse)(NotificationCCEventSupportedReport)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = NotificationCC;
  var NotificationCCEventSupportedGet2 = class extends _classSuper {
    static {
      __name(this, "NotificationCCEventSupportedGet");
    }
    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);
      NotificationCCEventSupportedGet2 = _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.notificationType = options.notificationType;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 1);
      const notificationType = raw.payload[0];
      return new this({
        nodeId: ctx.sourceNodeId,
        notificationType
      });
    }
    notificationType;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([this.notificationType]);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "notification type": (0, import_core.getNotificationName)(this.notificationType)
        }
      };
    }
  };
  return NotificationCCEventSupportedGet2 = _classThis;
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  NotificationCC,
  NotificationCCAPI,
  NotificationCCEventSupportedGet,
  NotificationCCEventSupportedReport,
  NotificationCCGet,
  NotificationCCReport,
  NotificationCCSet,
  NotificationCCSupportedGet,
  NotificationCCSupportedReport,
  NotificationCCValues,
  getNotificationEnumBehavior,
  getNotificationStateValueWithEnum,
  getNotificationValueMetadata,
  shouldAutoCreateSyntheticDoorSensorValue
});
//# sourceMappingURL=NotificationCC.js.map
