"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var parse_exports = {};
__export(parse_exports, {
  parseQRCodeString: () => parseQRCodeString
});
module.exports = __toCommonJS(parse_exports);
var import_shared = require("@zwave-js/shared");
var import_crypto = require("../crypto/index.js");
var import_SecurityClass = require("../definitions/SecurityClass.js");
var import_dsk = require("../dsk/index.js");
var import_ZWaveError = require("../error/ZWaveError.js");
var import_Primitive = require("../values/Primitive.js");
var import_definitions = require("./definitions.js");
var import_utils = require("./utils.js");
const qrCodeCandidateRegex = new RegExp(`90\\d{${import_definitions.minQRCodeLength - 2},}`, "g");
async function computeChecksum(qr, endOffset = qr.length) {
  const checksumInput = new TextEncoder().encode(qr.slice(9, endOffset));
  const hashResult = await (0, import_crypto.digest)("sha-1", checksumInput);
  return import_shared.Bytes.view(hashResult).readUInt16BE(0);
}
__name(computeChecksum, "computeChecksum");
async function parseQRCodeStringInternal(qr, parseSubsets) {
  if (!qr.startsWith("90"))
    (0, import_utils.fail)("must start with 90");
  if (qr.length < import_definitions.minQRCodeLength)
    (0, import_utils.fail)("too short");
  if (!import_definitions.onlyDigitsRegex.test(qr))
    (0, import_utils.fail)("contains invalid characters");
  const version = (0, import_utils.readLevel)(qr, 2);
  if (version > import_definitions.QRCodeVersion.SmartStart)
    (0, import_utils.fail)("invalid version");
  const expectedChecksum = (0, import_utils.readUInt16)(qr, 4);
  if (!parseSubsets) {
    if (await computeChecksum(qr, qr.length) !== expectedChecksum) {
      (0, import_utils.fail)("invalid checksum");
    }
  }
  const requestedKeysBitmask = (0, import_utils.readUInt8)(qr, 9);
  const requestedSecurityClasses = (0, import_Primitive.parseBitMask)([requestedKeysBitmask], import_SecurityClass.SecurityClass.S2_Unauthenticated);
  if (!requestedSecurityClasses.every((k) => k in import_SecurityClass.SecurityClass)) {
    (0, import_utils.fail)("invalid security class requested");
  }
  let offset = 12;
  const dsk = new import_shared.Bytes(16);
  for (let dskBlock = 0; dskBlock < 8; dskBlock++) {
    const block = (0, import_utils.readUInt16)(qr, offset);
    dsk.writeUInt16BE(block, dskBlock * 2);
    offset += 5;
  }
  const ret = {
    version,
    // This seems like a duplication, but it's more convenient for applications to not have to copy this field over
    requestedSecurityClasses,
    securityClasses: [...requestedSecurityClasses],
    dsk: (0, import_dsk.dskToString)(dsk)
  };
  let hasProductID = false;
  let hasProductType = false;
  while (offset + 4 <= qr.length) {
    const tlvLength = parseInt(qr.slice(offset + 2, offset + 4), 10);
    if (offset + 4 + tlvLength > qr.length)
      break;
    const { entry: { type, ...data }, charsRead } = (0, import_utils.parseTLV)(qr.slice(offset));
    offset += charsRead;
    if (type === import_definitions.ProvisioningInformationType.ProductId) {
      hasProductID = true;
    } else if (type === import_definitions.ProvisioningInformationType.ProductType) {
      hasProductType = true;
    }
    Object.assign(ret, data);
    if (parseSubsets && hasProductID && hasProductType && await computeChecksum(qr, offset) === expectedChecksum) {
      return ret;
    }
  }
  if (!hasProductID || !hasProductType) {
    (0, import_utils.fail)("missing required fields");
  }
  if (await computeChecksum(qr, offset) !== expectedChecksum) {
    (0, import_utils.fail)("invalid checksum");
  }
  return ret;
}
__name(parseQRCodeStringInternal, "parseQRCodeStringInternal");
async function parseQRCodeString(qr) {
  const normalized = qr.replaceAll(/\s/g, "");
  try {
    return await parseQRCodeStringInternal(normalized, false);
  } catch (e) {
    if (!(e instanceof import_ZWaveError.ZWaveError) || e.code !== import_ZWaveError.ZWaveErrorCodes.Security2CC_InvalidQRCode) {
      throw e;
    }
  }
  const regex = new RegExp(qrCodeCandidateRegex);
  let match;
  while ((match = regex.exec(normalized)) !== null) {
    try {
      return await parseQRCodeStringInternal(match[0], true);
    } catch (e) {
      if (!(e instanceof import_ZWaveError.ZWaveError) || e.code !== import_ZWaveError.ZWaveErrorCodes.Security2CC_InvalidQRCode) {
        throw e;
      }
      regex.lastIndex = match.index + 2;
    }
  }
  (0, import_utils.fail)("no valid QR code found");
}
__name(parseQRCodeString, "parseQRCodeString");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  parseQRCodeString
});
//# sourceMappingURL=parse.js.map
