"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 SceneControllerConfigurationCC_exports = {};
__export(SceneControllerConfigurationCC_exports, {
  SceneControllerConfigurationCC: () => SceneControllerConfigurationCC,
  SceneControllerConfigurationCCAPI: () => SceneControllerConfigurationCCAPI,
  SceneControllerConfigurationCCGet: () => SceneControllerConfigurationCCGet,
  SceneControllerConfigurationCCReport: () => SceneControllerConfigurationCCReport,
  SceneControllerConfigurationCCSet: () => SceneControllerConfigurationCCSet,
  SceneControllerConfigurationCCValues: () => import_CCValues_generated.SceneControllerConfigurationCCValues
});
module.exports = __toCommonJS(SceneControllerConfigurationCC_exports);
var import_tslib = require("tslib");
var __validateArgs = __toESM(require("./SceneControllerConfigurationCC._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_AssociationCC = require("./AssociationCC.js");
var import_CCValues_generated = require("./_CCValues.generated.js");
const { validateArgs_SceneControllerConfigurationCCAPI_disable, validateArgs_SceneControllerConfigurationCCAPI_set, validateArgs_SceneControllerConfigurationCCAPI_get } = __validateArgs;
let SceneControllerConfigurationCCAPI = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.API)(import_core.CommandClasses["Scene Controller Configuration"])];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_API.CCAPI;
  let _instanceExtraInitializers = [];
  let _disable_decorators;
  let _set_decorators;
  let _get_decorators;
  var SceneControllerConfigurationCCAPI2 = class extends _classSuper {
    static {
      __name(this, "SceneControllerConfigurationCCAPI");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      _disable_decorators = [validateArgs_SceneControllerConfigurationCCAPI_disable()];
      _set_decorators = [validateArgs_SceneControllerConfigurationCCAPI_set()];
      _get_decorators = [validateArgs_SceneControllerConfigurationCCAPI_get()];
      (0, import_tslib.__esDecorate)(this, null, _disable_decorators, { kind: "method", name: "disable", static: false, private: false, access: { has: /* @__PURE__ */ __name((obj) => "disable" in obj, "has"), get: /* @__PURE__ */ __name((obj) => obj.disable, "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, _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)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      SceneControllerConfigurationCCAPI2 = _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.SceneControllerConfigurationCommand.Get:
          return this.isSinglecast();
        case import_Types.SceneControllerConfigurationCommand.Set:
          return true;
      }
      return super.supportsCommand(cmd);
    }
    get [import_API.SET_VALUE]() {
      return async function({ property, propertyKey }, value, options) {
        if (propertyKey == void 0) {
          (0, import_API.throwMissingPropertyKey)(this.ccId, property);
        } else if (typeof propertyKey !== "number") {
          (0, import_API.throwUnsupportedPropertyKey)(this.ccId, property, propertyKey);
        }
        if (property === "sceneId") {
          if (typeof value !== "number") {
            (0, import_API.throwWrongValueType)(this.ccId, property, "number", typeof value);
          }
          if (value === 0) {
            return this.disable(propertyKey);
          } else {
            const dimmingDuration = import_core.Duration.from(options?.transitionDuration) ?? this.tryGetValueDB()?.getValue(import_CCValues_generated.SceneControllerConfigurationCCValues.dimmingDuration(propertyKey).endpoint(this.endpoint.index)) ?? import_core.Duration.default();
            return this.set(propertyKey, value, dimmingDuration);
          }
        } else if (property === "dimmingDuration") {
          if (typeof value !== "string" && !import_core.Duration.isDuration(value)) {
            (0, import_API.throwWrongValueType)(this.ccId, property, "duration", typeof value);
          }
          const dimmingDuration = import_core.Duration.from(value);
          if (dimmingDuration == void 0) {
            throw new import_core.ZWaveError(`${(0, import_core.getCCName)(this.ccId)}: "${property}" could not be set. ${JSON.stringify(value)} is not a valid duration.`, import_core.ZWaveErrorCodes.Argument_Invalid);
          }
          const valueDB = this.tryGetValueDB();
          const sceneId = valueDB?.getValue(import_CCValues_generated.SceneControllerConfigurationCCValues.sceneId(propertyKey).endpoint(this.endpoint.index));
          if (sceneId == void 0 || sceneId === 0) {
            if (valueDB) {
              const dimmingDurationValueId = import_CCValues_generated.SceneControllerConfigurationCCValues.dimmingDuration(propertyKey).endpoint(this.endpoint.index);
              valueDB.setValue(dimmingDurationValueId, dimmingDuration);
            }
            return;
          }
          return this.set(propertyKey, sceneId, dimmingDuration);
        } else {
          (0, import_API.throwUnsupportedProperty)(this.ccId, property);
        }
      };
    }
    get [import_API.POLL_VALUE]() {
      return async function({ property, propertyKey }) {
        switch (property) {
          case "sceneId":
          case "dimmingDuration": {
            if (propertyKey == void 0) {
              (0, import_API.throwMissingPropertyKey)(this.ccId, property);
            } else if (typeof propertyKey !== "number") {
              (0, import_API.throwUnsupportedPropertyKey)(this.ccId, property, propertyKey);
            }
            return (await this.get(propertyKey))?.[property];
          }
          default:
            (0, import_API.throwUnsupportedProperty)(this.ccId, property);
        }
      };
    }
    async disable(groupId) {
      this.assertSupportsCommand(import_Types.SceneControllerConfigurationCommand, import_Types.SceneControllerConfigurationCommand.Set);
      return this.set(groupId, 0, new import_core.Duration(0, "seconds"));
    }
    async set(groupId, sceneId, dimmingDuration) {
      this.assertSupportsCommand(import_Types.SceneControllerConfigurationCommand, import_Types.SceneControllerConfigurationCommand.Set);
      if (!this.endpoint.virtual) {
        const groupCount = SceneControllerConfigurationCC.getGroupCountCached(this.host, this.endpoint);
        if (groupId < 1 || groupId > groupCount) {
          throw new import_core.ZWaveError(`${this.constructor.name}: The group ID must be between 1 and the number of supported groups ${groupCount}.`, import_core.ZWaveErrorCodes.Argument_Invalid);
        }
      } else if (groupId < 1) {
        throw new import_core.ZWaveError(`The group ID must be greater than 0.`, import_core.ZWaveErrorCodes.Argument_Invalid);
      }
      const cc = new SceneControllerConfigurationCCSet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        groupId,
        sceneId,
        dimmingDuration
      });
      return this.host.sendCommand(cc, this.commandOptions);
    }
    async getLastActivated() {
      this.assertSupportsCommand(import_Types.SceneControllerConfigurationCommand, import_Types.SceneControllerConfigurationCommand.Get);
      const cc = new SceneControllerConfigurationCCGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        groupId: 0
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      if (response) {
        return (0, import_shared.pick)(response, ["groupId", "sceneId", "dimmingDuration"]);
      }
    }
    async get(groupId) {
      this.assertSupportsCommand(import_Types.SceneControllerConfigurationCommand, import_Types.SceneControllerConfigurationCommand.Get);
      if (groupId === 0) {
        throw new import_core.ZWaveError(`Invalid group ID 0. To get the last activated group / scene, use getLastActivated() instead.`, import_core.ZWaveErrorCodes.Argument_Invalid);
      } else if (groupId < 0) {
        throw new import_core.ZWaveError(`The group ID must be greater than 0.`, import_core.ZWaveErrorCodes.Argument_Invalid);
      }
      const cc = new SceneControllerConfigurationCCGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        groupId
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      if (response) {
        return (0, import_shared.pick)(response, ["sceneId", "dimmingDuration"]);
      }
    }
    constructor() {
      super(...arguments);
      (0, import_tslib.__runInitializers)(this, _instanceExtraInitializers);
    }
  };
  return SceneControllerConfigurationCCAPI2 = _classThis;
})();
let SceneControllerConfigurationCC = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.commandClass)(import_core.CommandClasses["Scene Controller Configuration"]), (0, import_CommandClassDecorators.implementedVersion)(1), (0, import_CommandClassDecorators.ccValues)(import_CCValues_generated.SceneControllerConfigurationCCValues)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_CommandClass.CommandClass;
  var SceneControllerConfigurationCC2 = class extends _classSuper {
    static {
      __name(this, "SceneControllerConfigurationCC");
    }
    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);
      SceneControllerConfigurationCC2 = _classThis = _classDescriptor.value;
      if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
      (0, import_tslib.__runInitializers)(_classThis, _classExtraInitializers);
    }
    determineRequiredCCInterviews() {
      return [
        ...super.determineRequiredCCInterviews(),
        import_core.CommandClasses.Association
      ];
    }
    async interview(ctx) {
      const node = this.getNode(ctx);
      const endpoint = this.getEndpoint(ctx);
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: `Interviewing ${this.ccName}...`,
        direction: "none"
      });
      const groupCount = SceneControllerConfigurationCC2.getGroupCountCached(ctx, endpoint);
      if (groupCount === 0) {
        ctx.logNode(node.id, {
          endpoint: this.endpointIndex,
          message: `skipping Scene Controller Configuration interview because Association group count is unknown`,
          direction: "none",
          level: "warn"
        });
        return;
      }
      for (let groupId = 1; groupId <= groupCount; groupId++) {
        const sceneIdValue = import_CCValues_generated.SceneControllerConfigurationCCValues.sceneId(groupId);
        this.ensureMetadata(ctx, sceneIdValue);
        const dimmingDurationValue = import_CCValues_generated.SceneControllerConfigurationCCValues.dimmingDuration(groupId);
        this.ensureMetadata(ctx, dimmingDurationValue);
      }
      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["Scene Controller Configuration"], ctx, endpoint).withOptions({
        priority: options?.priority ?? import_core.MessagePriority.NodeQuery
      });
      const groupCount = SceneControllerConfigurationCC2.getGroupCountCached(ctx, endpoint);
      ctx.logNode(node.id, {
        message: "querying all scene controller configurations...",
        direction: "outbound"
      });
      for (let groupId = 1; groupId <= groupCount; groupId++) {
        ctx.logNode(node.id, {
          endpoint: this.endpointIndex,
          message: `querying scene configuration for group #${groupId}...`,
          direction: "outbound"
        });
        const group = await api.get(groupId);
        if (group != void 0) {
          const logMessage = `received scene configuration for group #${groupId}:
scene ID:         ${group.sceneId}
dimming duration: ${group.dimmingDuration.toString()}`;
          ctx.logNode(node.id, {
            endpoint: this.endpointIndex,
            message: logMessage,
            direction: "inbound"
          });
        }
      }
    }
    /**
     * Returns the number of association groups reported by the node.
     * This only works AFTER the node has been interviewed by this CC
     * or the AssociationCC.
     */
    static getGroupCountCached(ctx, endpoint) {
      return ctx.getDeviceConfig?.(endpoint.nodeId)?.compat?.forceSceneControllerGroupCount ?? import_AssociationCC.AssociationCC.getGroupCountCached(ctx, endpoint) ?? 0;
    }
  };
  return SceneControllerConfigurationCC2 = _classThis;
})();
let SceneControllerConfigurationCCSet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.SceneControllerConfigurationCommand.Set), (0, import_CommandClassDecorators.useSupervision)()];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = SceneControllerConfigurationCC;
  var SceneControllerConfigurationCCSet2 = class extends _classSuper {
    static {
      __name(this, "SceneControllerConfigurationCCSet");
    }
    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);
      SceneControllerConfigurationCCSet2 = _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.groupId = options.groupId;
      this.sceneId = options.sceneId;
      this.dimmingDuration = import_core.Duration.from(options.dimmingDuration) ?? import_core.Duration.default();
    }
    static from(_raw, _ctx) {
      throw new import_core.ZWaveError(`${this.name}: deserialization not implemented`, import_core.ZWaveErrorCodes.Deserialization_NotImplemented);
    }
    groupId;
    sceneId;
    dimmingDuration;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([
        this.groupId,
        this.sceneId,
        this.dimmingDuration.serializeSet()
      ]);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "group id": this.groupId,
          "scene id": this.sceneId,
          "dimming duration": this.dimmingDuration.toString()
        }
      };
    }
  };
  return SceneControllerConfigurationCCSet2 = _classThis;
})();
let SceneControllerConfigurationCCReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.SceneControllerConfigurationCommand.Report)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = SceneControllerConfigurationCC;
  var SceneControllerConfigurationCCReport2 = class extends _classSuper {
    static {
      __name(this, "SceneControllerConfigurationCCReport");
    }
    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);
      SceneControllerConfigurationCCReport2 = _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.groupId = options.groupId;
      this.sceneId = options.sceneId;
      this.dimmingDuration = options.dimmingDuration;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 3);
      const groupId = raw.payload[0];
      const sceneId = raw.payload[1];
      const dimmingDuration = import_core.Duration.parseReport(raw.payload[2]) ?? import_core.Duration.unknown();
      return new this({
        nodeId: ctx.sourceNodeId,
        groupId,
        sceneId,
        dimmingDuration
      });
    }
    groupId;
    sceneId;
    dimmingDuration;
    persistValues(ctx) {
      if (!super.persistValues(ctx))
        return false;
      if (this.groupId === 0)
        return false;
      const sceneIdValue = import_CCValues_generated.SceneControllerConfigurationCCValues.sceneId(this.groupId);
      this.ensureMetadata(ctx, sceneIdValue);
      const dimmingDurationValue = import_CCValues_generated.SceneControllerConfigurationCCValues.dimmingDuration(this.groupId);
      this.ensureMetadata(ctx, dimmingDurationValue);
      this.setValue(ctx, sceneIdValue, this.sceneId);
      this.setValue(ctx, dimmingDurationValue, this.dimmingDuration);
      return true;
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "group id": this.groupId,
          "scene id": this.sceneId,
          "dimming duration": this.dimmingDuration.toString()
        }
      };
    }
  };
  return SceneControllerConfigurationCCReport2 = _classThis;
})();
function testResponseForSceneControllerConfigurationGet(sent, received) {
  return sent.groupId === 0 || received.groupId === sent.groupId;
}
__name(testResponseForSceneControllerConfigurationGet, "testResponseForSceneControllerConfigurationGet");
let SceneControllerConfigurationCCGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.SceneControllerConfigurationCommand.Get), (0, import_CommandClassDecorators.expectedCCResponse)(SceneControllerConfigurationCCReport, testResponseForSceneControllerConfigurationGet)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = SceneControllerConfigurationCC;
  var SceneControllerConfigurationCCGet2 = class extends _classSuper {
    static {
      __name(this, "SceneControllerConfigurationCCGet");
    }
    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);
      SceneControllerConfigurationCCGet2 = _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.groupId = options.groupId;
    }
    static from(_raw, _ctx) {
      throw new import_core.ZWaveError(`${this.name}: deserialization not implemented`, import_core.ZWaveErrorCodes.Deserialization_NotImplemented);
    }
    groupId;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([this.groupId]);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: { "group id": this.groupId }
      };
    }
  };
  return SceneControllerConfigurationCCGet2 = _classThis;
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SceneControllerConfigurationCC,
  SceneControllerConfigurationCCAPI,
  SceneControllerConfigurationCCGet,
  SceneControllerConfigurationCCReport,
  SceneControllerConfigurationCCSet,
  SceneControllerConfigurationCCValues
});
//# sourceMappingURL=SceneControllerConfigurationCC.js.map
