"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
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 ClientNodeStores_exports = {};
__export(ClientNodeStores_exports, {
  ClientNodeStores: () => ClientNodeStores
});
module.exports = __toCommonJS(ClientNodeStores_exports);
var import_general = require("@matter/general");
var import_ClientNodeStore = require("./ClientNodeStore.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const CLIENT_ID_PREFIX = "peer";
class ClientNodeStores {
  #storage;
  #stores = {};
  #construction;
  #nextAutomaticId = 1;
  get construction() {
    return this.#construction;
  }
  constructor(storage) {
    this.#storage = storage;
    this.#construction = (0, import_general.Construction)(this);
    this.#construction.start();
  }
  async [import_general.Construction.construct]() {
    const contexts = await this.#storage.contexts();
    for (const id of contexts) {
      if (!id.startsWith(CLIENT_ID_PREFIX)) {
        continue;
      }
      const num = Number.parseInt(id.slice(CLIENT_ID_PREFIX.length));
      if (Number.isFinite(num)) {
        if (this.#nextAutomaticId <= num) {
          this.#nextAutomaticId = num + 1;
        }
      }
      this.#createNodeStore(id, true);
    }
    await import_general.MatterAggregateError.allSettled(
      Object.values(this.#stores).map((store) => store.construction.ready),
      "Error while initializing client stores"
    );
  }
  /**
   * Allocate a stable local ID for a peer.
   *
   * The ID may be preassigned or we will assign using an incrementing sequential number.  The number is reserved for
   * the life of this process or, if data is persisted, until erased.
   */
  allocateId() {
    this.#construction.assert();
    return `${CLIENT_ID_PREFIX}${this.#nextAutomaticId++}`;
  }
  /**
   * Get the store for a single {@link ClientNode} or peer Id.
   *
   * These stores are cached internally by Id.
   */
  storeForNode(nodeOrId) {
    this.#construction.assert();
    if (typeof nodeOrId !== "string") {
      nodeOrId = nodeOrId.id;
    }
    const store = this.#stores[nodeOrId];
    if (store) {
      return store;
    }
    return this.#createNodeStore(nodeOrId);
  }
  storeForGroup(node) {
    this.#construction.assert();
    const store = this.#stores[node.id];
    if (store) {
      return store;
    }
    return this.#createGroupStore(node.id);
  }
  /**
   * List all nodes present.
   */
  get knownIds() {
    this.#construction.assert();
    return Object.keys(this.#stores);
  }
  async close() {
    await this.construction;
  }
  /**
   * Group stores are always created with a memory backend as they are transient.
   */
  #createGroupStore(id) {
    const manager = new import_general.StorageManager(new import_general.MemoryStorageDriver());
    manager.initialize();
    const store = new import_ClientNodeStore.ClientNodeStore(id, manager.createContext(id), false);
    store.construction.start();
    this.#stores[id] = store;
    return store;
  }
  #createNodeStore(id, isPreexisting = false) {
    const store = new import_ClientNodeStore.ClientNodeStore(
      id,
      this.#storage.createContext(id),
      isPreexisting,
      () => delete this.#stores[id]
    );
    store.construction.start();
    this.#stores[id] = store;
    return store;
  }
}
//# sourceMappingURL=ClientNodeStores.js.map
