"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 PartialCCSessionManager_exports = {};
__export(PartialCCSessionManager_exports, {
  PartialCCSessionManager: () => PartialCCSessionManager
});
module.exports = __toCommonJS(PartialCCSessionManager_exports);
var import_shared = require("@zwave-js/shared");
class PartialCCSessionManager {
  static {
    __name(this, "PartialCCSessionManager");
  }
  constructor(host) {
    this.host = host;
  }
  host;
  sessions = /* @__PURE__ */ new Map();
  drains = /* @__PURE__ */ new Map();
  /**
   * Determines if the given command belongs to a partial CC session and tracks it if so.
   * Returns `undefined` for commands that do not support partial sessions.
   */
  handleCommand(command, msg) {
    const sessionId = command.getPartialCCSessionId();
    if (!sessionId)
      return void 0;
    const remaining = command.getRemainingSegments() ?? 0;
    const key = JSON.stringify({
      nodeId: command.nodeId,
      ccId: command.ccId,
      ccCommand: command.ccCommand,
      ...sessionId
    });
    const drain = this.drains.get(key);
    if (drain) {
      if (remaining <= drain.nextRemaining) {
        if (remaining === 0) {
          this.deleteDrain(key);
        } else {
          drain.nextRemaining = remaining - 1;
        }
        return { type: "segment", duplicate: true };
      }
      this.deleteDrain(key);
    }
    let session = this.sessions.get(key);
    if (!session) {
      if (remaining === 0) {
        return {
          type: "complete",
          command,
          partials: [],
          finalMsg: msg
        };
      }
      session = {
        nodeId: command.nodeId,
        segments: /* @__PURE__ */ new Map(),
        lastSegmentMsg: msg,
        requestCC: this.host.findRequestCC(command),
        attemptsLeft: this.host.getMaxReRequestAttempts()
      };
      this.sessions.set(key, session);
    }
    if (session.segments.size > 0 && remaining > Math.max(...session.segments.keys())) {
      session.segments.clear();
      session.finalMsg = void 0;
    }
    const duplicate = session.segments.has(remaining);
    session.segments.set(remaining, command);
    session.lastSegmentMsg = msg;
    if (remaining === 0)
      session.finalMsg = msg;
    const expectedTotal = Math.max(...session.segments.keys()) + 1;
    if (session.segments.has(0) && session.segments.size === expectedTotal) {
      this.deleteSession(key);
      if (remaining > 0) {
        this.deleteDrain(key);
        this.drains.set(key, {
          nextRemaining: remaining - 1,
          timeout: (0, import_shared.setTimer)(() => {
            this.drains.delete(key);
          }, this.host.getSegmentTimeout())
        });
      }
      const partials = [...session.segments.entries()].filter(([rem]) => rem > 0).toSorted(([a], [b]) => b - a).map(([, cc]) => cc);
      return {
        type: "complete",
        command: session.segments.get(0),
        partials,
        finalMsg: session.finalMsg
      };
    }
    session.timeout?.clear();
    session.timeout = (0, import_shared.setTimer)(() => {
      this.recoverOrDrop(key, session);
    }, this.host.getSegmentTimeout());
    return { type: "segment", duplicate };
  }
  /** Re-requests the response a session belongs to, or drops the session when that is not possible */
  recoverOrDrop(key, session) {
    if (session.requestCC && session.attemptsLeft > 0) {
      session.attemptsLeft--;
      this.host.rerequestSession(session);
      session.timeout?.clear();
      session.timeout = (0, import_shared.setTimer)(() => {
        this.recoverOrDrop(key, session);
      }, this.host.getSegmentTimeout());
    } else {
      this.deleteSession(key);
      this.host.onSessionLost(session);
    }
  }
  deleteSession(key) {
    const session = this.sessions.get(key);
    if (session) {
      session.timeout?.clear();
      this.sessions.delete(key);
    }
  }
  deleteDrain(key) {
    const drain = this.drains.get(key);
    if (drain) {
      drain.timeout.clear();
      this.drains.delete(key);
    }
  }
  /** Drops all sessions and stops all timers */
  clear() {
    for (const session of this.sessions.values()) {
      session.timeout?.clear();
    }
    this.sessions.clear();
    for (const drain of this.drains.values()) {
      drain.timeout.clear();
    }
    this.drains.clear();
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PartialCCSessionManager
});
//# sourceMappingURL=PartialCCSessionManager.js.map
