/**
 * @license
 * Copyright 2022-2024 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { Endpoint } from "#endpoint/Endpoint.js";
import { EndpointServer } from "#endpoint/EndpointServer.js";
import { EndpointInitializer } from "#endpoint/properties/EndpointInitializer.js";
import { InternalError, Logger } from "#general";
import { DescriptorServer } from "../../behaviors/descriptor/DescriptorServer.js";
import { NodeStore } from "../storage/NodeStore.js";
const logger = Logger.get("BehaviorInit");
class ServerEndpointInitializer extends EndpointInitializer {
  #store;
  constructor(environment) {
    super();
    this.#store = environment.get(NodeStore);
  }
  initializeDescendent(endpoint) {
    if (!endpoint.lifecycle.hasId) {
      endpoint.id = this.#identifyPart(endpoint);
    }
    this.#store.endpointStores.assignNumber(endpoint);
    endpoint.behaviors.require(DescriptorServer);
  }
  /**
   * If a {@link Endpoint} does not yet have a {@link EndpointServer}, create one now, then create a
   * {@link BehaviorBacking} for a specific {@link Behavior}.
   *
   * This is where we adapt endpoints and behaviors for a server role.
   */
  createBacking(endpoint, behavior) {
    return EndpointServer.forEndpoint(endpoint).createBacking(behavior);
  }
  /**
   * Select an ID for an endpoint automatically based on available metadata.
   */
  #identifyPart(endpoint) {
    const basicInfo = endpoint.behaviors.supported.basicInformation ?? endpoint.behaviors.supported.bridgedDeviceBasicInformation;
    if (basicInfo) {
      const defaults = {
        ...new basicInfo.State(),
        ...endpoint.behaviors.defaultsFor(basicInfo)
      };
      let id2 = defaults.uniqueId;
      if (id2) {
        return id2;
      }
      id2 = defaults.serialNumber;
      if (id2) {
        return id2;
      }
    }
    if (!(endpoint.owner instanceof Endpoint)) {
      throw new InternalError("Cannot determine ID for endpoint with unknown parent type");
    }
    if (!endpoint.owner.lifecycle.hasId) {
      throw new InternalError("Cannot determine ID for endpoint because parent has no ID");
    }
    const index = endpoint.owner.parts.indexOf(endpoint);
    if (index === -1) {
      throw new InternalError("Cannot determine ID for endpoint because parent does not list as child");
    }
    const id = `part${index}`;
    logger.warn(`Using fallback ID of ${id} for child of ${endpoint.owner}; assign ID to remove this warning`);
    return id;
  }
}
export {
  ServerEndpointInitializer
};
//# sourceMappingURL=ServerEndpointInitializer.js.map
