/**
 * @license
 * Copyright 2022-2024 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import {
  Construction,
  Diagnostic,
  ImplementationError,
  Logger,
  StorageService,
  asyncNew
} from "#general";
const logger = Logger.get("ControllerStore");
class ControllerStore {
  #location;
  #nodeId;
  #storageManager;
  #sessionStorage;
  #credentialsStorage;
  // Root certificate and Fabric
  #nodesStorage;
  // Holds list of nodes in root level and then sub levels with data per client node?
  #construction;
  get construction() {
    return this.#construction;
  }
  /**
   * Create a new store.
   *
   * TODO - implement conversion from 0.7 format so people can change API seamlessly
   */
  constructor(environment, nodeId) {
    if (nodeId === void 0) {
      throw new ImplementationError("ServerStore must be created with a nodeId");
    }
    const storage = environment.get(StorageService);
    this.#location = storage.location ?? "(unknown location)";
    this.#nodeId = nodeId;
    const initializeStorage = async () => {
      this.#storageManager = await storage.open(nodeId);
      this.#logChange("Opened");
    };
    this.#construction = Construction(this, initializeStorage);
  }
  static async create(environment, nodeId) {
    return await asyncNew(this, environment, nodeId);
  }
  async erase() {
    await this.#sessionStorage?.clearAll();
    await this.#credentialsStorage?.clearAll();
    await this.#nodesStorage?.clearAll();
  }
  async close() {
    await this.#construction.close(async () => {
      await this.#storageManager?.close();
      this.#logChange("Closed");
    });
  }
  get sessionStorage() {
    if (!this.#sessionStorage) {
      this.#sessionStorage = this.storage.createContext("sessions");
    }
    return this.#sessionStorage;
  }
  get credentialsStorage() {
    if (!this.#credentialsStorage) {
      this.#credentialsStorage = this.storage.createContext("credentials");
    }
    return this.#credentialsStorage;
  }
  get nodesStorage() {
    if (this.#nodesStorage === void 0) {
      this.#nodesStorage = this.storage.createContext("nodes");
    }
    return this.#nodesStorage;
  }
  get storage() {
    if (this.#storageManager === void 0) {
      throw new ImplementationError("Node storage accessed prior to initialization");
    }
    return this.#storageManager;
  }
  #logChange(what) {
    logger.info(what, Diagnostic.strong(this.#nodeId ?? "node"), "storage at", `${this.#location}/${this.#nodeId}`);
  }
}
export {
  ControllerStore
};
//# sourceMappingURL=ControllerStore.js.map
