"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 BinarySwitchCC_exports = {};
__export(BinarySwitchCC_exports, {
  BinarySwitchCC: () => BinarySwitchCC,
  BinarySwitchCCAPI: () => BinarySwitchCCAPI,
  BinarySwitchCCGet: () => BinarySwitchCCGet,
  BinarySwitchCCReport: () => BinarySwitchCCReport,
  BinarySwitchCCSet: () => BinarySwitchCCSet,
  BinarySwitchCCValues: () => import_CCValues_generated.BinarySwitchCCValues
});
module.exports = __toCommonJS(BinarySwitchCC_exports);
var import_tslib = require("tslib");
var __validateArgs = __toESM(require("./BinarySwitchCC._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_BinarySwitchCCAPI_set } = __validateArgs;
let BinarySwitchCCAPI = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.API)(import_core.CommandClasses["Binary Switch"])];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_API.CCAPI;
  let _instanceExtraInitializers = [];
  let _set_decorators;
  var BinarySwitchCCAPI2 = class extends _classSuper {
    static {
      __name(this, "BinarySwitchCCAPI");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      (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)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      BinarySwitchCCAPI2 = _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.BinarySwitchCommand.Get:
          return this.isSinglecast();
        case import_Types.BinarySwitchCommand.Set:
          return true;
      }
      return super.supportsCommand(cmd);
    }
    // oxlint-disable-next-line typescript/explicit-module-boundary-types
    async get() {
      this.assertSupportsCommand(import_Types.BinarySwitchCommand, import_Types.BinarySwitchCommand.Get);
      const cc = new BinarySwitchCCGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      if (response) {
        return {
          // interpret unknown values as false
          currentValue: response.currentValue || false,
          targetValue: response.targetValue,
          duration: response.duration
        };
      }
    }
    /**
     * Sets the switch to the given value
     * @param targetValue The target value to set
     * @param duration The duration after which the target value should be reached. Can be a Duration instance or a user-friendly duration string like `"1m17s"`. Only supported in V2 and above.
     */
    async set(targetValue, duration) {
      this.assertSupportsCommand(import_Types.BinarySwitchCommand, import_Types.BinarySwitchCommand.Set);
      const cc = new BinarySwitchCCSet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        targetValue,
        duration
      });
      return this.host.sendCommand(cc, this.commandOptions);
    }
    get [(_set_decorators = [validateArgs_BinarySwitchCCAPI_set()], import_API.SET_VALUE)]() {
      return async function({ property }, value, options) {
        if (property !== "targetValue") {
          (0, import_API.throwUnsupportedProperty)(this.ccId, property);
        }
        if (typeof value !== "boolean") {
          (0, import_API.throwWrongValueType)(this.ccId, property, "boolean", typeof value);
        }
        const duration = import_core.Duration.from(options?.transitionDuration);
        return this.set(value, duration);
      };
    }
    [import_API.SET_VALUE_HOOKS] = ((0, import_tslib.__runInitializers)(this, _instanceExtraInitializers), ({ property }, value, options) => {
      if (property === "targetValue") {
        const currentValueValueId = import_CCValues_generated.BinarySwitchCCValues.currentValue.endpoint(this.endpoint.index);
        return {
          // This is the target value for a split target/current state pair.
          isSplitStateTargetValue: true,
          optimisticallyUpdateRelatedValues: /* @__PURE__ */ __name((_supervisedAndSuccessful) => {
            if (this.isSinglecast()) {
              this.tryGetValueDB()?.setValue(currentValueValueId, value);
            } else if (this.isMulticast()) {
              const affectedNodes = this.endpoint.node.physicalNodes.filter((node) => node.getEndpoint(this.endpoint.index)?.supportsCC(this.ccId));
              for (const node of affectedNodes) {
                this.host.tryGetValueDB(node.id)?.setValue(currentValueValueId, value);
              }
            }
          }, "optimisticallyUpdateRelatedValues"),
          verifyChanges: /* @__PURE__ */ __name(() => {
            if (this.isSinglecast()) {
              this.schedulePoll(currentValueValueId, value, {
                duration: import_core.Duration.from(options?.transitionDuration),
                // on/off "transitions" are usually fast
                transition: "fast"
              });
            } else {
            }
          }, "verifyChanges")
        };
      }
    });
    get [import_API.POLL_VALUE]() {
      return async function({ property }) {
        switch (property) {
          case "currentValue":
          case "targetValue":
          case "duration":
            return (await this.get())?.[property];
          default:
            (0, import_API.throwUnsupportedProperty)(this.ccId, property);
        }
      };
    }
  };
  return BinarySwitchCCAPI2 = _classThis;
})();
let BinarySwitchCC = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.commandClass)(import_core.CommandClasses["Binary Switch"]), (0, import_CommandClassDecorators.implementedVersion)(2), (0, import_CommandClassDecorators.ccValues)(import_CCValues_generated.BinarySwitchCCValues)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_CommandClass.CommandClass;
  var BinarySwitchCC2 = class extends _classSuper {
    static {
      __name(this, "BinarySwitchCC");
    }
    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);
      BinarySwitchCC2 = _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);
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: `Interviewing ${this.ccName}...`,
        direction: "none"
      });
      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 Switch"], ctx, endpoint).withOptions({
        priority: options?.priority ?? import_core.MessagePriority.NodeQuery
      });
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: "querying Binary Switch state...",
        direction: "outbound"
      });
      const resp = await api.get();
      if (resp) {
        let logMessage = `received Binary Switch state:
current value:      ${resp.currentValue}`;
        if (resp.targetValue != void 0) {
          logMessage += `
target value:       ${resp.targetValue}
remaining duration: ${resp.duration?.toString() ?? "undefined"}`;
        }
        ctx.logNode(node.id, {
          endpoint: this.endpointIndex,
          message: logMessage,
          direction: "inbound"
        });
      }
    }
    setMappedBasicValue(ctx, value) {
      this.setValue(ctx, import_CCValues_generated.BinarySwitchCCValues.currentValue, value > 0);
      return true;
    }
  };
  return BinarySwitchCC2 = _classThis;
})();
let BinarySwitchCCSet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.BinarySwitchCommand.Set), (0, import_CommandClassDecorators.useSupervision)()];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = BinarySwitchCC;
  var BinarySwitchCCSet2 = class extends _classSuper {
    static {
      __name(this, "BinarySwitchCCSet");
    }
    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);
      BinarySwitchCCSet2 = _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.targetValue = options.targetValue;
      this.duration = import_core.Duration.from(options.duration);
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 1);
      const targetValue = !!raw.payload[0];
      let duration;
      if (raw.payload.length >= 2) {
        duration = import_core.Duration.parseSet(raw.payload[1]);
      }
      return new this({
        nodeId: ctx.sourceNodeId,
        targetValue,
        duration
      });
    }
    targetValue;
    duration;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([
        this.targetValue ? 255 : 0,
        (this.duration ?? import_core.Duration.default()).serializeSet()
      ]);
      const ccVersion = (0, import_CommandClass.getEffectiveCCVersion)(ctx, this);
      if (ccVersion < 2 && ctx.getDeviceConfig?.(this.nodeId)?.compat?.encodeCCsUsingTargetVersion) {
        this.payload = this.payload.subarray(0, 1);
      }
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      const message = {
        "target value": this.targetValue
      };
      if (this.duration != void 0) {
        message.duration = this.duration.toString();
      }
      return {
        ...super.toLogEntry(ctx),
        message
      };
    }
  };
  return BinarySwitchCCSet2 = _classThis;
})();
let BinarySwitchCCReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.BinarySwitchCommand.Report), (0, import_CommandClassDecorators.ccValueProperty)("currentValue", import_CCValues_generated.BinarySwitchCCValues.currentValue), (0, import_CommandClassDecorators.ccValueProperty)("targetValue", import_CCValues_generated.BinarySwitchCCValues.targetValue), (0, import_CommandClassDecorators.ccValueProperty)("duration", import_CCValues_generated.BinarySwitchCCValues.duration)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = BinarySwitchCC;
  var BinarySwitchCCReport2 = class extends _classSuper {
    static {
      __name(this, "BinarySwitchCCReport");
    }
    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);
      BinarySwitchCCReport2 = _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.currentValue = options.currentValue;
      this.targetValue = options.targetValue;
      this.duration = import_core.Duration.from(options.duration);
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 1);
      const currentValue = (0, import_core.parseMaybeBoolean)(raw.payload[0]);
      let targetValue;
      let duration;
      if (raw.payload.length >= 3) {
        targetValue = (0, import_core.parseMaybeBoolean)(raw.payload[1]);
        duration = import_core.Duration.parseReport(raw.payload[2]);
      }
      return new this({
        nodeId: ctx.sourceNodeId,
        currentValue,
        targetValue,
        duration
      });
    }
    currentValue;
    targetValue;
    duration;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([
        (0, import_core.encodeMaybeBoolean)(this.currentValue ?? import_core.UNKNOWN_STATE)
      ]);
      if (this.targetValue !== void 0) {
        this.payload = import_shared.Bytes.concat([
          this.payload,
          [
            (0, import_core.encodeMaybeBoolean)(this.targetValue),
            (this.duration ?? import_core.Duration.default()).serializeReport()
          ]
        ]);
      }
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      const message = {
        "current value": (0, import_core.maybeUnknownToString)(this.currentValue)
      };
      if (this.targetValue !== void 0) {
        message["target value"] = (0, import_core.maybeUnknownToString)(this.targetValue);
      }
      if (this.duration != void 0) {
        message.duration = this.duration.toString();
      }
      return {
        ...super.toLogEntry(ctx),
        message
      };
    }
  };
  return BinarySwitchCCReport2 = _classThis;
})();
let BinarySwitchCCGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.BinarySwitchCommand.Get), (0, import_CommandClassDecorators.expectedCCResponse)(BinarySwitchCCReport)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = BinarySwitchCC;
  var BinarySwitchCCGet2 = class extends _classSuper {
    static {
      __name(this, "BinarySwitchCCGet");
    }
    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);
      BinarySwitchCCGet2 = _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 BinarySwitchCCGet2 = _classThis;
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BinarySwitchCC,
  BinarySwitchCCAPI,
  BinarySwitchCCGet,
  BinarySwitchCCReport,
  BinarySwitchCCSet,
  BinarySwitchCCValues
});
//# sourceMappingURL=BinarySwitchCC.js.map
