"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 DoorLockLoggingCC_exports = {};
__export(DoorLockLoggingCC_exports, {
  DoorLockLoggingCC: () => DoorLockLoggingCC,
  DoorLockLoggingCCAPI: () => DoorLockLoggingCCAPI,
  DoorLockLoggingCCRecordGet: () => DoorLockLoggingCCRecordGet,
  DoorLockLoggingCCRecordReport: () => DoorLockLoggingCCRecordReport,
  DoorLockLoggingCCRecordsSupportedGet: () => DoorLockLoggingCCRecordsSupportedGet,
  DoorLockLoggingCCRecordsSupportedReport: () => DoorLockLoggingCCRecordsSupportedReport,
  DoorLockLoggingCCValues: () => import_CCValues_generated.DoorLockLoggingCCValues
});
module.exports = __toCommonJS(DoorLockLoggingCC_exports);
var import_tslib = require("tslib");
var __validateArgs = __toESM(require("./DoorLockLoggingCC._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_UserCodeCC = require("./UserCodeCC.js");
var import_CCValues_generated = require("./_CCValues.generated.js");
const { validateArgs_DoorLockLoggingCCAPI_getRecord } = __validateArgs;
function segmentsToDate(segments) {
  return new Date(
    segments.year,
    segments.month - 1,
    // JS months are 0-based.
    segments.day,
    segments.hour,
    segments.minute,
    segments.second
  );
}
__name(segmentsToDate, "segmentsToDate");
const eventTypeLabel = {
  LockCode: "Locked via Access Code",
  UnlockCode: "Unlocked via Access Code",
  LockButton: "Locked via Lock Button",
  UnlockButton: "Unlocked via Unlock Button",
  LockCodeOutOfSchedule: "Out of Schedule Lock Attempt via Access Code",
  UnlockCodeOutOfSchedule: "Out of Schedule Unlock Attempt via Access Code",
  IllegalCode: "Illegal Access Code Entered",
  LockManual: "Manually Locked",
  UnlockManual: "Manually Unlocked",
  LockAuto: "Auto Locked",
  UnlockAuto: "Auto Unlocked",
  LockRemoteCode: "Locked via Remote Access Code",
  UnlockRemoteCode: "Unlocked via Remote Access Code",
  LockRemote: "Locked via Remote",
  UnlockRemote: "Unlocked via Remote",
  LockRemoteCodeOutOfSchedule: "Out of Schedule Lock Attempt via Remote Access Code",
  UnlockRemoteCodeOutOfSchedule: "Out of Schedule Unlock Attempt via Remote Access Code",
  RemoteIllegalCode: "Illegal Remote Access Code",
  LockManual2: "Manually Locked (2)",
  UnlockManual2: "Manually Unlocked (2)",
  LockSecured: "Lock Secured",
  LockUnsecured: "Lock Unsecured",
  UserCodeAdded: "User Code Added",
  UserCodeDeleted: "User Code Deleted",
  AllUserCodesDeleted: "All User Codes Deleted",
  AdminCodeChanged: "Admin Code Changed",
  UserCodeChanged: "User Code Changed",
  LockReset: "Lock Reset",
  ConfigurationChanged: "Configuration Changed",
  LowBattery: "Low Battery",
  NewBattery: "New Battery Installed",
  Unknown: "Unknown"
};
const LATEST_RECORD_NUMBER_KEY = 0;
let DoorLockLoggingCCAPI = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.API)(import_core.CommandClasses["Door Lock Logging"])];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_API.PhysicalCCAPI;
  let _instanceExtraInitializers = [];
  let _getRecord_decorators;
  var DoorLockLoggingCCAPI2 = class extends _classSuper {
    static {
      __name(this, "DoorLockLoggingCCAPI");
    }
    static {
      _classThis = this;
    }
    static {
      const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
      _getRecord_decorators = [validateArgs_DoorLockLoggingCCAPI_getRecord()];
      (0, import_tslib.__esDecorate)(this, null, _getRecord_decorators, { kind: "method", name: "getRecord", static: false, private: false, access: { has: /* @__PURE__ */ __name((obj) => "getRecord" in obj, "has"), get: /* @__PURE__ */ __name((obj) => obj.getRecord, "get") }, metadata: _metadata }, null, _instanceExtraInitializers);
      (0, import_tslib.__esDecorate)(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
      DoorLockLoggingCCAPI2 = _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.DoorLockLoggingCommand.RecordsSupportedGet:
        case import_Types.DoorLockLoggingCommand.RecordsSupportedReport:
        case import_Types.DoorLockLoggingCommand.RecordGet:
        case import_Types.DoorLockLoggingCommand.RecordReport:
          return true;
      }
      return super.supportsCommand(cmd);
    }
    async getRecordsCount() {
      this.assertSupportsCommand(import_Types.DoorLockLoggingCommand, import_Types.DoorLockLoggingCommand.RecordsSupportedGet);
      const cc = new DoorLockLoggingCCRecordsSupportedGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      return response?.recordsCount;
    }
    /** Retrieves the specified audit record. Defaults to the latest one. */
    async getRecord(recordNumber = LATEST_RECORD_NUMBER_KEY) {
      this.assertSupportsCommand(import_Types.DoorLockLoggingCommand, import_Types.DoorLockLoggingCommand.RecordGet);
      const cc = new DoorLockLoggingCCRecordGet({
        nodeId: this.endpoint.nodeId,
        endpointIndex: this.endpoint.index,
        recordNumber
      });
      const response = await this.host.sendCommand(cc, this.commandOptions);
      return response?.record;
    }
    constructor() {
      super(...arguments);
      (0, import_tslib.__runInitializers)(this, _instanceExtraInitializers);
    }
  };
  return DoorLockLoggingCCAPI2 = _classThis;
})();
let DoorLockLoggingCC = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.commandClass)(import_core.CommandClasses["Door Lock Logging"]), (0, import_CommandClassDecorators.implementedVersion)(1), (0, import_CommandClassDecorators.ccValues)(import_CCValues_generated.DoorLockLoggingCCValues)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = import_CommandClass.CommandClass;
  var DoorLockLoggingCC2 = class extends _classSuper {
    static {
      __name(this, "DoorLockLoggingCC");
    }
    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);
      DoorLockLoggingCC2 = _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["Door Lock Logging"], ctx, endpoint).withOptions({
        priority: options?.priority ?? import_core.MessagePriority.NodeQuery
      });
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: "querying supported number of records...",
        direction: "outbound"
      });
      const recordsCount = await api.getRecordsCount();
      if (!recordsCount) {
        ctx.logNode(node.id, {
          endpoint: this.endpointIndex,
          message: "Door Lock Logging records count query timed out, skipping interview...",
          level: "warn"
        });
        return;
      }
      const recordsCountLogMessage = `supports ${recordsCount} record${recordsCount === 1 ? "" : "s"}`;
      ctx.logNode(node.id, {
        endpoint: this.endpointIndex,
        message: recordsCountLogMessage,
        direction: "inbound"
      });
    }
  };
  return DoorLockLoggingCC2 = _classThis;
})();
let DoorLockLoggingCCRecordsSupportedReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.DoorLockLoggingCommand.RecordsSupportedReport), (0, import_CommandClassDecorators.ccValueProperty)("recordsCount", import_CCValues_generated.DoorLockLoggingCCValues.recordsCount)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = DoorLockLoggingCC;
  var DoorLockLoggingCCRecordsSupportedReport2 = class extends _classSuper {
    static {
      __name(this, "DoorLockLoggingCCRecordsSupportedReport");
    }
    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);
      DoorLockLoggingCCRecordsSupportedReport2 = _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.recordsCount = options.recordsCount;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 1);
      const recordsCount = raw.payload[0];
      return new this({
        nodeId: ctx.sourceNodeId,
        recordsCount
      });
    }
    recordsCount;
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: {
          "supported no. of records": this.recordsCount
        }
      };
    }
  };
  return DoorLockLoggingCCRecordsSupportedReport2 = _classThis;
})();
function eventTypeToLabel(eventType) {
  return eventTypeLabel[import_Types.DoorLockLoggingEventType[eventType]] ?? `Unknown ${(0, import_shared.num2hex)(eventType)}`;
}
__name(eventTypeToLabel, "eventTypeToLabel");
let DoorLockLoggingCCRecordsSupportedGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.DoorLockLoggingCommand.RecordsSupportedGet), (0, import_CommandClassDecorators.expectedCCResponse)(DoorLockLoggingCCRecordsSupportedReport)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = DoorLockLoggingCC;
  var DoorLockLoggingCCRecordsSupportedGet2 = class extends _classSuper {
    static {
      __name(this, "DoorLockLoggingCCRecordsSupportedGet");
    }
    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);
      DoorLockLoggingCCRecordsSupportedGet2 = _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 DoorLockLoggingCCRecordsSupportedGet2 = _classThis;
})();
let DoorLockLoggingCCRecordReport = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.DoorLockLoggingCommand.RecordReport)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = DoorLockLoggingCC;
  var DoorLockLoggingCCRecordReport2 = class extends _classSuper {
    static {
      __name(this, "DoorLockLoggingCCRecordReport");
    }
    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);
      DoorLockLoggingCCRecordReport2 = _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.recordNumber = options.recordNumber;
      this.record = options.record;
    }
    static from(raw, ctx) {
      (0, import_core.validatePayload)(raw.payload.length >= 11);
      const recordNumber = raw.payload[0];
      const recordStatus = raw.payload[5] >>> 5;
      let record;
      if (recordStatus !== import_Types.DoorLockLoggingRecordStatus.Empty) {
        const dateSegments = {
          year: raw.payload.readUInt16BE(1),
          month: raw.payload[3],
          day: raw.payload[4],
          hour: raw.payload[5] & 31,
          minute: raw.payload[6],
          second: raw.payload[7]
        };
        const eventType = raw.payload[8];
        const recordUserID = raw.payload[9];
        const userCodeLength = raw.payload[10];
        (0, import_core.validatePayload)(userCodeLength <= 10, raw.payload.length >= 11 + userCodeLength);
        const userCodeBuffer = raw.payload.subarray(11, 11 + userCodeLength);
        const userCodeString = userCodeBuffer.toString("utf8");
        const userCode = (0, import_shared.isPrintableASCII)(userCodeString) ? userCodeString : userCodeBuffer;
        record = {
          eventType,
          label: eventTypeToLabel(eventType),
          timestamp: segmentsToDate(dateSegments).toISOString(),
          userId: recordUserID,
          userCode
        };
      }
      return new this({
        nodeId: ctx.sourceNodeId,
        recordNumber,
        record
      });
    }
    recordNumber;
    record;
    toLogEntry(ctx) {
      let message;
      if (!this.record) {
        message = {
          "record #": `${this.recordNumber} (empty)`
        };
      } else {
        message = {
          "record #": `${this.recordNumber}`,
          "event type": this.record.label,
          timestamp: this.record.timestamp
        };
        if (this.record.userId) {
          message["user ID"] = this.record.userId;
        }
        if (this.record.userCode) {
          message["user code"] = (0, import_UserCodeCC.userCodeToLogString)(this.record.userCode);
        }
      }
      return {
        ...super.toLogEntry(ctx),
        message
      };
    }
  };
  return DoorLockLoggingCCRecordReport2 = _classThis;
})();
function testResponseForDoorLockLoggingRecordGet(sent, received) {
  return sent.recordNumber === LATEST_RECORD_NUMBER_KEY || sent.recordNumber === received.recordNumber;
}
__name(testResponseForDoorLockLoggingRecordGet, "testResponseForDoorLockLoggingRecordGet");
let DoorLockLoggingCCRecordGet = (() => {
  let _classDecorators = [(0, import_CommandClassDecorators.CCCommand)(import_Types.DoorLockLoggingCommand.RecordGet), (0, import_CommandClassDecorators.expectedCCResponse)(DoorLockLoggingCCRecordReport, testResponseForDoorLockLoggingRecordGet)];
  let _classDescriptor;
  let _classExtraInitializers = [];
  let _classThis;
  let _classSuper = DoorLockLoggingCC;
  var DoorLockLoggingCCRecordGet2 = class extends _classSuper {
    static {
      __name(this, "DoorLockLoggingCCRecordGet");
    }
    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);
      DoorLockLoggingCCRecordGet2 = _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.recordNumber = options.recordNumber;
    }
    static from(_raw, _ctx) {
      throw new import_core.ZWaveError(`${this.name}: deserialization not implemented`, import_core.ZWaveErrorCodes.Deserialization_NotImplemented);
    }
    recordNumber;
    serialize(ctx) {
      this.payload = import_shared.Bytes.from([this.recordNumber]);
      return super.serialize(ctx);
    }
    toLogEntry(ctx) {
      return {
        ...super.toLogEntry(ctx),
        message: { "record number": this.recordNumber }
      };
    }
  };
  return DoorLockLoggingCCRecordGet2 = _classThis;
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  DoorLockLoggingCC,
  DoorLockLoggingCCAPI,
  DoorLockLoggingCCRecordGet,
  DoorLockLoggingCCRecordReport,
  DoorLockLoggingCCRecordsSupportedGet,
  DoorLockLoggingCCRecordsSupportedReport,
  DoorLockLoggingCCValues
});
//# sourceMappingURL=DoorLockLoggingCC.js.map
