"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 EndpointStore_exports = {};
__export(EndpointStore_exports, {
  EndpointStore: () => EndpointStore
});
module.exports = __toCommonJS(EndpointStore_exports);
var import_DatasourceStore = require("#endpoint/storage/DatasourceStore.js");
var import_general = require("#general");
/**
 * @license
 * Copyright 2022-2024 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const NUMBER_KEY = "__number__";
class EndpointStore {
  #storage;
  initialValues = {};
  #number;
  #construction;
  #childStorage;
  #childStores = {};
  #knownBehaviors = /* @__PURE__ */ new Set();
  /**
   * Description used in diagnostic messages.
   */
  toString() {
    return `storage:${this.#storage.thisContexts.join(".")}`;
  }
  get construction() {
    return this.#construction;
  }
  get number() {
    this.#construction.assert();
    return this.#number;
  }
  set number(number) {
    this.#construction.assert();
    if (this.#number !== number) {
      this.#number = number;
    }
  }
  constructor(storage, load = true) {
    this.#storage = storage;
    this.#childStorage = storage.createContext("parts");
    this.#construction = (0, import_general.Construction)(this, () => {
      if (!load) {
        return;
      }
      return this.#load();
    });
  }
  async #load() {
    this.#knownBehaviors = new Set(await this.#storage.contexts());
    for (const behaviorId of this.#knownBehaviors) {
      const behaviorValues = this.initialValues[behaviorId] = {};
      const behaviorStorage = this.#storage.createContext(behaviorId);
      const storedValues = await behaviorStorage.values();
      for (const [key, value] of Object.entries(storedValues)) {
        if (value !== void 0) {
          behaviorValues[key] = value;
        }
      }
    }
    const number = await this.#storage.get(NUMBER_KEY, -1);
    if (number !== -1) {
      this.#number = number;
    }
    await this.#loadSubparts();
  }
  /**
   * Invoke a function on this store and the stores of descendant parts.
   */
  visit(fn) {
    fn(this);
    for (const child of Object.values(this.#childStores)) {
      child.visit(fn);
    }
  }
  /**
   * Obtain a {@link Datasource.Store} for a behavior.
   */
  storeForBehavior(behaviorId) {
    this.#construction.assert();
    const initialValues = this.initialValues[behaviorId];
    if (initialValues !== void 0) {
      delete this.initialValues[behaviorId];
    }
    return (0, import_DatasourceStore.DatasourceStore)(this, behaviorId, initialValues);
  }
  childStoreFor(endpoint) {
    if (!endpoint.lifecycle.hasId) {
      throw new import_general.ImplementationError("Cannot access endpoint storage because endpoint has no assigned ID");
    }
    return this.storeForPartId(endpoint.id);
  }
  storeForPartId(partId) {
    this.#construction.assert();
    let store = this.#childStores[partId];
    if (store === void 0) {
      store = this.#childStores[partId] = new EndpointStore(this.#childStorage.createContext(partId), false);
    }
    return store;
  }
  async saveNumber() {
    await this.#construction;
    await this.#storage.set(NUMBER_KEY, this.number);
  }
  /**
   * Patch values.  Keyed by {@link Behavior.id} then property name.
   *
   * See {@link Datasource.Store.set} for the patch semantics the individual structs use.
   */
  async set(values) {
    await this.#construction;
    for (const behaviorId in values) {
      const behaviorValues = values[behaviorId];
      const behaviorStorage = this.#storage.createContext(behaviorId);
      if (behaviorValues === void 0) {
        if (this.#knownBehaviors.has(behaviorId)) {
          await behaviorStorage.clearAll();
          this.#knownBehaviors.delete(behaviorId);
        }
        continue;
      }
      if (!this.#knownBehaviors.has(behaviorId)) {
        this.#knownBehaviors.add(behaviorId);
      }
      const toSave = {};
      let keysToSave = 0;
      for (const key in behaviorValues) {
        const value = behaviorValues[key];
        if (value === void 0) {
          await behaviorStorage.delete(key);
        } else {
          toSave[key] = value;
          keysToSave++;
        }
      }
      if (keysToSave > 0) {
        await behaviorStorage.set(toSave);
      }
    }
  }
  /**
   * Remove all persisted information for the {@link Endpoint}
   */
  async erase() {
    await this.#construction;
    await this.#storage.clearAll();
  }
  async #loadSubparts() {
    const knownParts = await this.#childStorage.contexts();
    for (const partId of knownParts) {
      await this.#loadKnownChildStores(partId);
    }
  }
  async #loadKnownChildStores(partId) {
    const endpointStore = new EndpointStore(this.#childStorage.createContext(partId));
    this.#childStores[partId] = endpointStore;
    await endpointStore.construction;
  }
}
//# sourceMappingURL=EndpointStore.js.map
