"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 BinarySensorCC_exports = {};
__export(BinarySensorCC_exports, {
  BinarySensorCC: () => BinarySensorCC,
  BinarySensorCCAPI: () => BinarySensorCCAPI,
  BinarySensorCCGet: () => BinarySensorCCGet,
  BinarySensorCCReport: () => BinarySensorCCReport,
  BinarySensorCCSupportedGet: () => BinarySensorCCSupportedGet,
  BinarySensorCCSupportedReport: () => BinarySensorCCSupportedReport,
  BinarySensorCCValues: () => import_CCValues_generated.BinarySensorCCValues
});
module.exports = __toCommonJS(BinarySensorCC_exports);
var import_tslib = require("tslib");
var __validateArgs = __toESM(require("./BinarySensorCC._validateArgs.js"), 1);
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");
const { validateArgs_BinarySensorCCAPI_get, validateArgs_BinarySensorCCAPI_sendReport, validateArgs_BinarySensorCCAPI_reportSupportedSensorTypes } = __validateArgs;
let BinarySensorCCAPI = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.API)(import_core.CommandClasses["Binary Sensor"])];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_API.PhysicalCCAPI;
  let _instanceExtraInitializers = [];
  let _get_decorators;
  let _sendReport_decorators;
  let _reportSupportedSensorTypes_decorators;
  var BinarySensorCCAPI2 = class extends _classSuper {
    static {
      __name(this, "BinarySensorCCAPI");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      _get_decorators = [validateArgs_BinarySensorCCAPI_get()];
      _sendReport_decorators = [validateArgs_BinarySensorCCAPI_sendReport()];
      _reportSupportedSensorTypes_decorators = [validateArgs_BinarySensorCCAPI_reportSupportedSensorTypes()];
      (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, _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, _reportSupportedSensorTypes_decorators, { kind: "method", name: "reportSupportedSensorTypes", static: false, private: false, access: { has: /* @__PURE__ */ __name((obj) => "reportSupportedSensorTypes" in obj, "has"), get: /* @__PURE__ */ __name((obj) => obj.reportSupportedSensorTypes, "get") }, metadata: _metadata }, null, _instanceExtraInitializers);
      (0, import_tslib.__esDecorate)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      BinarySensorCCAPI2 = _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.BinarySensorCommand.Get:
        case import_Types.BinarySensorCommand.Report:
          return true;
        // This is mandatory
        case import_Types.BinarySensorCommand.SupportedGet:
        case import_Types.BinarySensorCommand.SupportedReport:
          return this.version >= 2;
      }
      return super.supportsCommand(cmd);
    }
    get [import_API.POLL_VALUE]() {
      return async function({ property }) {
        if (typeof property === "string") {
          const sensorType = import_Types.BinarySensorType[property];
          if (sensorType)
            return this.get(sensorType);
        }
        (0, import_API.throwUnsupportedProperty)(this.ccId, property);
      };
    }
    /**
     * Retrieves the current value from this sensor
     * @param sensorType The (optional) sensor type to retrieve the value for
     */
    async get(sensorType) {
      this.assertSupportsCommand(import_Types.BinarySensorCommand, import_Types.BinarySensorCommand.Get);
      const cc = new BinarySensorCCGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        sensorType
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      return response?.value;
    }
    async sendReport(value, sensorType) {
      this.assertSupportsCommand(import_Types.BinarySensorCommand, import_Types.BinarySensorCommand.Report);
      const cc = new BinarySensorCCReport({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        value,
        type: sensorType
      });
      return this.host.sendCommand(cc, this.commandOptions);
    }
    async getSupportedSensorTypes() {
      this.assertSupportsCommand(import_Types.BinarySensorCommand, import_Types.BinarySensorCommand.SupportedGet);
      const cc = new BinarySensorCCSupportedGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      return response?.supportedSensorTypes;
    }
    async reportSupportedSensorTypes(supported) {
      this.assertSupportsCommand(import_Types.BinarySensorCommand, import_Types.BinarySensorCommand.SupportedReport);
      const cc = new BinarySensorCCSupportedReport({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        supportedSensorTypes: supported
      });
      return this.host.sendCommand(cc, this.commandOptions);
    }
    constructor() {
      super(...arguments);
      (0, import_tslib.__runInitializers)(this, _instanceExtraInitializers);
    }
  };
  return BinarySensorCCAPI2 = _classThis;
})();
let BinarySensorCC = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.commandClass)(import_core.CommandClasses["Binary Sensor"]), (0, import_CommandClassDecorators.implementedVersion)(2), (0, import_CommandClassDecorators.ccValues)(import_CCValues_generated.BinarySensorCCValues)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_CommandClass.CommandClass;
  var BinarySensorCC2 = class extends _classSuper {
    static {
      __name(this, "BinarySensorCC");
    }
    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);
      BinarySensorCC2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    async interview(ctx) {
      const node = this.getNode(ctx);
      const endpoint = this.getEndpoint(ctx);
      const api = import_API.CCAPI.create(import_core.CommandClasses["Binary Sensor"], ctx, endpoint).withOptions({
        priority: import_core.MessagePriority.NodeQuery
      });
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: `Interviewing ${this.ccName}...`,
        direction: "none"
      });
      if (api.version >= 2) {
        ctx.logNode(node.id, {
          endpoint: this.endpointIndex,
          message: "querying supported sensor types...",
          direction: "outbound"
        });
        const supportedSensorTypes = await api.getSupportedSensorTypes();
        if (supportedSensorTypes) {
          const logMessage = `received supported sensor types: ${supportedSensorTypes.map((type) => (0, import_shared.getEnumMemberName)(import_Types.BinarySensorType, type)).map((name) => `
\xB7 ${name}`).join("")}`;
          ctx.logNode(node.id, {
            endpoint: this.endpointIndex,
            message: logMessage,
            direction: "inbound"
          });
        } else {
          ctx.logNode(node.id, {
            endpoint: this.endpointIndex,
            message: "Querying supported sensor types timed out, skipping interview...",
            level: "warn"
          });
          return;
        }
      }
      await this.refreshValues(ctx);
      this.setInterviewComplete(ctx, true);
    }
    async refreshValues(ctx, options) {
      const node = this.getNode(ctx);
      const endpoint = this.getEndpoint(ctx);
      const api = import_API.CCAPI.create(import_core.CommandClasses["Binary Sensor"], ctx, endpoint).withOptions({
        priority: options?.priority ?? import_core.MessagePriority.NodeQuery
      });
      if (api.version === 1) {
        ctx.logNode(node.id, {
          endpoint: this.endpointIndex,
          message: "querying current value...",
          direction: "outbound"
        });
        const currentValue = await api.get();
        if (currentValue != void 0) {
          ctx.logNode(node.id, {
            endpoint: this.endpointIndex,
            message: `received current value: ${currentValue}`,
            direction: "inbound"
          });
        }
      } else {
        const supportedSensorTypes = this.getValue(ctx, import_CCValues_generated.BinarySensorCCValues.supportedSensorTypes) ?? [];
        for (const type of supportedSensorTypes) {
          if (!(0, import_shared.isEnumMember)(import_Types.BinarySensorType, type))
            continue;
          const sensorName = (0, import_shared.getEnumMemberName)(import_Types.BinarySensorType, type);
          ctx.logNode(node.id, {
            endpoint: this.endpointIndex,
            message: `querying current value for ${sensorName}...`,
            direction: "outbound"
          });
          const currentValue = await api.get(type);
          if (currentValue != void 0) {
            ctx.logNode(node.id, {
              endpoint: this.endpointIndex,
              message: `received current value for ${sensorName}: ${currentValue}`,
              direction: "inbound"
            });
          }
        }
      }
    }
    /**
     * Returns which sensor types are supported.
     * This only works AFTER the interview process
     */
    static getSupportedSensorTypesCached(ctx, endpoint) {
      return ctx.getValueDB(endpoint.nodeId).getValue(import_CCValues_generated.BinarySensorCCValues.supportedSensorTypes.endpoint(endpoint.index));
    }
    setMappedBasicValue(ctx, value) {
      const valueDB = this.getValueDB(ctx);
      const anyValueId = import_CCValues_generated.BinarySensorCCValues.state(import_Types.BinarySensorType.Any).endpoint(this.endpointIndex);
      let sensorType;
      if (valueDB.hasMetadata(anyValueId)) {
        sensorType = import_Types.BinarySensorType.Any;
      } else {
        const existingSensorTypes = valueDB.getAllMetadata(import_core.CommandClasses["Binary Sensor"]).filter((v) => v.endpoint === this.endpointIndex && import_CCValues_generated.BinarySensorCCValues.state.is(v)).map((v) => v.metadata?.ccSpecific?.sensorType).filter((t) => t != void 0).toSorted((a, b) => a - b);
        sensorType = existingSensorTypes[0] ?? import_Types.BinarySensorType.Any;
      }
      const binarySensorValue = import_CCValues_generated.BinarySensorCCValues.state(sensorType);
      this.setValue(ctx, binarySensorValue, value > 0);
      return true;
    }
  };
  return BinarySensorCC2 = _classThis;
})();
let BinarySensorCCReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.BinarySensorCommand.Report)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = BinarySensorCC;
  var BinarySensorCCReport2 = class extends _classSuper {
    static {
      __name(this, "BinarySensorCCReport");
    }
    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);
      BinarySensorCCReport2 = _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.type = options.type ?? import_Types.BinarySensorType.Any;
      this.value = options.value;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 1);
      const value = raw.payload[0] === 255;
      let type = import_Types.BinarySensorType.Any;
      if (raw.payload.length >= 2) {
        type = raw.payload[1];
      }
      return new this({
        nodeId: ctx.sourceNodeId,
        value,
        type
      });
    }
    persistValues(ctx) {
      if (!super.persistValues(ctx))
        return false;
      let sensorType = this.type;
      if (sensorType === import_Types.BinarySensorType.Any) {
        const supportedSensorTypes = this.getValue(ctx, import_CCValues_generated.BinarySensorCCValues.supportedSensorTypes);
        if (supportedSensorTypes?.length) {
          sensorType = supportedSensorTypes[0];
        }
      }
      const binarySensorValue = import_CCValues_generated.BinarySensorCCValues.state(sensorType);
      this.setMetadata(ctx, binarySensorValue, binarySensorValue.meta);
      this.setValue(ctx, binarySensorValue, this.value);
      return true;
    }
    type;
    value;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([this.value ? 255 : 0, this.type]);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          type: (0, import_shared.getEnumMemberName)(import_Types.BinarySensorType, this.type),
          value: this.value
        }
      };
    }
  };
  return BinarySensorCCReport2 = _classThis;
})();
function testResponseForBinarySensorGet(sent, received) {
  return sent.sensorType == void 0 || sent.sensorType === import_Types.BinarySensorType.Any || received.type === sent.sensorType || received.type === import_Types.BinarySensorType.Any;
}
__name(testResponseForBinarySensorGet, "testResponseForBinarySensorGet");
let BinarySensorCCGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.BinarySensorCommand.Get), (0, import_CommandClassDecorators.expectedCCResponse)(BinarySensorCCReport, testResponseForBinarySensorGet)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = BinarySensorCC;
  var BinarySensorCCGet2 = class extends _classSuper {
    static {
      __name(this, "BinarySensorCCGet");
    }
    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);
      BinarySensorCCGet2 = _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.sensorType = options.sensorType;
    }
    static from(raw, ctx) {
      let sensorType;
      if (raw.payload.length >= 1) {
        sensorType = raw.payload[0];
      }
      return new this({
        nodeId: ctx.sourceNodeId,
        sensorType
      });
    }
    sensorType;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([this.sensorType ?? import_Types.BinarySensorType.Any]);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          type: (0, import_shared.getEnumMemberName)(import_Types.BinarySensorType, this.sensorType ?? import_Types.BinarySensorType.Any)
        }
      };
    }
  };
  return BinarySensorCCGet2 = _classThis;
})();
let BinarySensorCCSupportedReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.BinarySensorCommand.SupportedReport), (0, import_CommandClassDecorators.ccValueProperty)("supportedSensorTypes", import_CCValues_generated.BinarySensorCCValues.supportedSensorTypes)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = BinarySensorCC;
  var BinarySensorCCSupportedReport2 = class extends _classSuper {
    static {
      __name(this, "BinarySensorCCSupportedReport");
    }
    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);
      BinarySensorCCSupportedReport2 = _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.supportedSensorTypes = options.supportedSensorTypes;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 1);
      const supportedSensorTypes = (0, import_core.parseBitMask)(raw.payload, 0).filter((t) => t !== 0);
      return new this({
        nodeId: ctx.sourceNodeId,
        supportedSensorTypes
      });
    }
    supportedSensorTypes;
    serialize(ctx) {
      this.payload = (0, import_core.encodeBitMask)(this.supportedSensorTypes.filter((t) => t !== import_Types.BinarySensorType.Any), void 0, 0);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "supported types": this.supportedSensorTypes.map((type) => (0, import_shared.getEnumMemberName)(import_Types.BinarySensorType, type)).join(", ")
        }
      };
    }
  };
  return BinarySensorCCSupportedReport2 = _classThis;
})();
let BinarySensorCCSupportedGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.BinarySensorCommand.SupportedGet), (0, import_CommandClassDecorators.expectedCCResponse)(BinarySensorCCSupportedReport)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = BinarySensorCC;
  var BinarySensorCCSupportedGet2 = class extends _classSuper {
    static {
      __name(this, "BinarySensorCCSupportedGet");
    }
    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);
      BinarySensorCCSupportedGet2 = _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 BinarySensorCCSupportedGet2 = _classThis;
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BinarySensorCC,
  BinarySensorCCAPI,
  BinarySensorCCGet,
  BinarySensorCCReport,
  BinarySensorCCSupportedGet,
  BinarySensorCCSupportedReport,
  BinarySensorCCValues
});
//# sourceMappingURL=BinarySensorCC.js.map
