/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { isObject } from "@matter/general";
const NODE_SUBKEY = "nodes";
const BEHAVIOR_SUBKEY = "behaviors";
const PART_SUBKEY = "parts";
class EndpointVariableService {
  #env;
  #varsForEndpoint = /* @__PURE__ */ new WeakMap();
  #varsForBehavior = /* @__PURE__ */ new WeakMap();
  constructor(env) {
    this.#env = env;
  }
  /**
   * Access the variable map for an instance of a behavior.
   */
  forBehaviorInstance(endpoint, type) {
    const forAll = this.forBehaviorType(type);
    const forThisEndpoint = this.forEndpoint(endpoint);
    const forThis = forThisEndpoint[type.id] ?? forThisEndpoint[type.id.toLowerCase()];
    if (isObject(forThis)) {
      return { ...forAll, ...forThis };
    }
    return forAll;
  }
  /**
   * Access the variable map for an endpoint.
   */
  forEndpoint(endpoint) {
    if (!endpoint.lifecycle.hasId) {
      return {};
    }
    let vars = this.#varsForEndpoint.get(endpoint);
    if (vars !== void 0) {
      return vars;
    }
    let envVars;
    if (endpoint.owner === void 0) {
      envVars = this.#env.vars.get(`${NODE_SUBKEY}.${endpoint.id}`);
    } else if (!endpoint.lifecycle.isInstalled) {
      return {};
    } else {
      const partVars = this.forEndpoint(endpoint.owner)[PART_SUBKEY];
      if (isObject(partVars)) {
        envVars = partVars[endpoint.id];
      }
    }
    if (isObject(envVars)) {
      vars = envVars;
    } else {
      vars = {};
    }
    this.#varsForEndpoint.set(endpoint, vars);
    return vars;
  }
  /**
   * Access the variable map for a type of behavior.
   */
  forBehaviorType(type) {
    let vars = this.#varsForBehavior.get(type);
    if (vars !== void 0) {
      return vars;
    }
    let envVars = this.#env.vars.get(`${BEHAVIOR_SUBKEY}.${type.id}`);
    if (!isObject(envVars)) {
      envVars = this.#env.vars.get(type.id);
    }
    if (isObject(envVars)) {
      vars = envVars;
    } else {
      vars = {};
    }
    this.#varsForBehavior.set(type, vars);
    return vars;
  }
}
export {
  EndpointVariableService
};
//# sourceMappingURL=EndpointVariableService.js.map
