/**
 * @license
 * Copyright 2022-2024 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { Construction, ImplementationError } from "#general";
import { NodeActivity } from "../../context/NodeActivity.js";
import { NetworkBehavior } from "./NetworkBehavior.js";
class NetworkRuntime {
  #construction;
  #owner;
  get construction() {
    return this.#construction;
  }
  constructor(owner) {
    this.#owner = owner;
    const internals = owner.behaviors.internalsOf(NetworkBehavior);
    if (internals.runtime) {
      throw new ImplementationError("Network is already active");
    }
    internals.runtime = this;
    this.#construction = Construction(this);
  }
  async [Construction.construct]() {
    await this.start();
    await this.#owner.act((agent) => this.owner.lifecycle.online.emit(agent.context));
  }
  async [Construction.destruct]() {
    this.blockNewActivity();
    const activity = this.#owner.env.get(NodeActivity);
    if (activity.isActive) {
      await activity.inactive;
    }
    try {
      await this.stop();
    } finally {
      this.#owner.behaviors.internalsOf(NetworkBehavior).runtime = void 0;
    }
    await this.#owner.act((agent) => this.owner.lifecycle.offline.emit(agent.context));
  }
  async close() {
    await this.construction.close();
  }
  get owner() {
    return this.#owner;
  }
}
export {
  NetworkRuntime
};
//# sourceMappingURL=NetworkRuntime.js.map
