"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 TimeParametersCC_exports = {};
__export(TimeParametersCC_exports, {
  TimeParametersCC: () => TimeParametersCC,
  TimeParametersCCAPI: () => TimeParametersCCAPI,
  TimeParametersCCGet: () => TimeParametersCCGet,
  TimeParametersCCReport: () => TimeParametersCCReport,
  TimeParametersCCSet: () => TimeParametersCCSet,
  TimeParametersCCValues: () => import_CCValues_generated.TimeParametersCCValues
});
module.exports = __toCommonJS(TimeParametersCC_exports);
var import_tslib = require("tslib");
var __validateArgs = __toESM(require("./TimeParametersCC._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_TimeParametersCCAPI_set } = __validateArgs;
function shouldUseLocalTime(ctx, endpoint) {
  const forceUTC = !!ctx.getDeviceConfig?.(endpoint.nodeId)?.compat?.useUTCInTimeParametersCC;
  if (forceUTC)
    return false;
  const ccVersion = endpoint.getCCVersion(import_core.CommandClasses.Time);
  if (ccVersion >= 1 && endpoint.controlsCC(import_core.CommandClasses.Time)) {
    return false;
  }
  if (ccVersion >= 2 && endpoint.supportsCC(import_core.CommandClasses.Time)) {
    return false;
  }
  return true;
}
__name(shouldUseLocalTime, "shouldUseLocalTime");
function segmentsToDate(segments, local) {
  if (local) {
    return new Date(segments.year, segments.month - 1, segments.day, segments.hour, segments.minute, segments.second);
  } else {
    return new Date(Date.UTC(segments.year, segments.month - 1, segments.day, segments.hour, segments.minute, segments.second));
  }
}
__name(segmentsToDate, "segmentsToDate");
function dateToSegments(date, local) {
  return {
    year: date[`get${local ? "" : "UTC"}FullYear`](),
    month: date[`get${local ? "" : "UTC"}Month`]() + 1,
    day: date[`get${local ? "" : "UTC"}Date`](),
    hour: date[`get${local ? "" : "UTC"}Hours`](),
    minute: date[`get${local ? "" : "UTC"}Minutes`](),
    second: date[`get${local ? "" : "UTC"}Seconds`]()
  };
}
__name(dateToSegments, "dateToSegments");
let TimeParametersCCAPI = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.API)(import_core.CommandClasses["Time Parameters"])];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_API.CCAPI;
  let _instanceExtraInitializers = [];
  let _set_decorators;
  var TimeParametersCCAPI2 = class extends _classSuper {
    static {
      __name(this, "TimeParametersCCAPI");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      _set_decorators = [validateArgs_TimeParametersCCAPI_set()];
      (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);
      TimeParametersCCAPI2 = _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.TimeParametersCommand.Get:
          return this.isSinglecast();
        case import_Types.TimeParametersCommand.Set:
          return true;
      }
      return super.supportsCommand(cmd);
    }
    get [import_API.SET_VALUE]() {
      return async function({ property }, value) {
        if (property !== "dateAndTime") {
          (0, import_API.throwUnsupportedProperty)(this.ccId, property);
        }
        if (!(value instanceof Date)) {
          (0, import_API.throwWrongValueType)(this.ccId, property, "date", typeof value);
        }
        return this.set(value);
      };
    }
    get [import_API.POLL_VALUE]() {
      return async function({ property }) {
        switch (property) {
          case "dateAndTime":
            return this.get();
          default:
            (0, import_API.throwUnsupportedProperty)(this.ccId, property);
        }
      };
    }
    async get() {
      this.assertSupportsCommand(import_Types.TimeParametersCommand, import_Types.TimeParametersCommand.Get);
      const cc = new TimeParametersCCGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      return response?.dateAndTime;
    }
    async set(dateAndTime) {
      this.assertSupportsCommand(import_Types.TimeParametersCommand, import_Types.TimeParametersCommand.Set);
      const endpointToCheck = this.endpoint.virtual ? this.endpoint.node.physicalNodes[0].getEndpoint(this.endpoint.index) : this.endpoint;
      const useLocalTime = shouldUseLocalTime(this.host, endpointToCheck);
      const cc = new TimeParametersCCSet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        dateAndTime,
        useLocalTime
      });
      return this.host.sendCommand(cc, this.commandOptions);
    }
    constructor() {
      super(...arguments);
      (0, import_tslib.__runInitializers)(this, _instanceExtraInitializers);
    }
  };
  return TimeParametersCCAPI2 = _classThis;
})();
let TimeParametersCC = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.commandClass)(import_core.CommandClasses["Time Parameters"]), (0, import_CommandClassDecorators.implementedVersion)(1), (0, import_CommandClassDecorators.ccValues)(import_CCValues_generated.TimeParametersCCValues)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_CommandClass.CommandClass;
  var TimeParametersCC2 = class extends _classSuper {
    static {
      __name(this, "TimeParametersCC");
    }
    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);
      TimeParametersCC2 = _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["Time Parameters"], ctx, endpoint).withOptions({
        priority: import_core.MessagePriority.NodeQuery
      });
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: `Interviewing ${this.ccName}...`,
        direction: "none"
      });
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: "setting current time...",
        direction: "outbound"
      });
      await api.set(/* @__PURE__ */ new Date());
      this.setInterviewComplete(ctx, true);
    }
  };
  return TimeParametersCC2 = _classThis;
})();
let TimeParametersCCReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.TimeParametersCommand.Report), (0, import_CommandClassDecorators.ccValueProperty)("dateAndTime", import_CCValues_generated.TimeParametersCCValues.dateAndTime)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = TimeParametersCC;
  var TimeParametersCCReport2 = class extends _classSuper {
    static {
      __name(this, "TimeParametersCCReport");
    }
    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);
      TimeParametersCCReport2 = _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.dateAndTime = options.dateAndTime;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 7);
      const dateSegments = {
        year: raw.payload.readUInt16BE(0),
        month: raw.payload[2],
        day: raw.payload[3],
        hour: raw.payload[4],
        minute: raw.payload[5],
        second: raw.payload[6]
      };
      const dateAndTime = segmentsToDate(
        dateSegments,
        // Assume we can use UTC and correct this assumption in persistValues
        false
      );
      return new this({
        nodeId: ctx.sourceNodeId,
        dateAndTime
      });
    }
    persistValues(ctx) {
      const local = shouldUseLocalTime(ctx, this.getEndpoint(ctx));
      if (local) {
        const segments = dateToSegments(this.dateAndTime, false);
        this.dateAndTime = segmentsToDate(segments, local);
      }
      return super.persistValues(ctx);
    }
    dateAndTime;
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "date and time": (0, import_core.formatDate)(this.dateAndTime, "YYYY-MM-DD HH:mm:ss")
        }
      };
    }
  };
  return TimeParametersCCReport2 = _classThis;
})();
let TimeParametersCCGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.TimeParametersCommand.Get), (0, import_CommandClassDecorators.expectedCCResponse)(TimeParametersCCReport)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = TimeParametersCC;
  var TimeParametersCCGet2 = class extends _classSuper {
    static {
      __name(this, "TimeParametersCCGet");
    }
    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);
      TimeParametersCCGet2 = _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 TimeParametersCCGet2 = _classThis;
})();
let TimeParametersCCSet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.TimeParametersCommand.Set), (0, import_CommandClassDecorators.useSupervision)()];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = TimeParametersCC;
  var TimeParametersCCSet2 = class extends _classSuper {
    static {
      __name(this, "TimeParametersCCSet");
    }
    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);
      TimeParametersCCSet2 = _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.dateAndTime = options.dateAndTime;
      this.useLocalTime = options.useLocalTime;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 7);
      const dateSegments = {
        year: raw.payload.readUInt16BE(0),
        month: raw.payload[2],
        day: raw.payload[3],
        hour: raw.payload[4],
        minute: raw.payload[5],
        second: raw.payload[6]
      };
      (0, import_core.validatePayload)(dateSegments.month >= 1 && dateSegments.month <= 12, dateSegments.day >= 1 && dateSegments.day <= 31, dateSegments.hour >= 0 && dateSegments.hour <= 23, dateSegments.minute >= 0 && dateSegments.minute <= 59, dateSegments.second >= 0 && dateSegments.second <= 59);
      const dateAndTime = segmentsToDate(
        dateSegments,
        // Assume we can use UTC and correct this assumption in persistValues
        false
      );
      return new this({
        nodeId: ctx.sourceNodeId,
        dateAndTime
      });
    }
    persistValues(ctx) {
      const local = shouldUseLocalTime(ctx, this.getEndpoint(ctx));
      if (local) {
        const segments = dateToSegments(this.dateAndTime, false);
        this.dateAndTime = segmentsToDate(segments, local);
      }
      return super.persistValues(ctx);
    }
    dateAndTime;
    useLocalTime;
    serialize(ctx) {
      const dateSegments = dateToSegments(this.dateAndTime, !!this.useLocalTime);
      this.payload = import_shared.Bytes.from([
        // 2 bytes placeholder for year
        0,
        0,
        dateSegments.month,
        dateSegments.day,
        dateSegments.hour,
        dateSegments.minute,
        dateSegments.second
      ]);
      this.payload.writeUInt16BE(dateSegments.year, 0);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "date and time": (0, import_core.formatDate)(this.dateAndTime, "YYYY-MM-DD HH:mm:ss")
        }
      };
    }
  };
  return TimeParametersCCSet2 = _classThis;
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  TimeParametersCC,
  TimeParametersCCAPI,
  TimeParametersCCGet,
  TimeParametersCCReport,
  TimeParametersCCSet,
  TimeParametersCCValues
});
//# sourceMappingURL=TimeParametersCC.js.map
