/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { InternalError, MatterError, ObserverGroup } from "@matter/general";
import { ExchangeProvider, Peer, PeerAddress, PeerSet } from "@matter/protocol";
import { CommissioningClient } from "../commissioning/CommissioningClient.js";
import { NetworkRuntime } from "./NetworkRuntime.js";
class UncommissionedError extends MatterError {
}
class OfflineError extends MatterError {
}
class ClientNetworkRuntime extends NetworkRuntime {
  #observers = new ObserverGroup();
  #isReady = false;
  constructor(owner) {
    super(owner);
  }
  set isReady(isReady) {
    this.#isReady = isReady;
    this.#syncOnlineStatus();
  }
  get owner() {
    return super.owner;
  }
  async start() {
    if (!this.owner.lifecycle.isCommissioned) {
      throw new UncommissionedError(`Cannot interact with ${this.owner} because it is uncommissioned`);
    }
    if (this.owner.state.network.isDisabled) {
      throw new UncommissionedError(`Cannot interact with ${this.owner} because it is disabled`);
    }
    const address = PeerAddress(this.owner.stateOf(CommissioningClient).peerAddress);
    if (address === void 0) {
      throw new InternalError(`Commissioned node ${this.owner} has no peer address`);
    }
    const server = this.owner.owner;
    if (!server.lifecycle.isOnline) {
      await server.start();
    }
    const { env } = this.owner;
    const peers = env.get(PeerSet);
    const peer = peers.get(address);
    if (peer === void 0) {
      throw new InternalError(`Commissioned node ${this.owner} has no peer ${address.toString()} installed`);
    }
    env.set(ExchangeProvider, peer.exchangeProvider);
    const syncOnlineStatus = this.#syncOnlineStatus.bind(this);
    this.#observers.on(peer.sessions.added, syncOnlineStatus);
    this.#observers.on(peer.sessions.deleted, syncOnlineStatus);
  }
  async stop() {
    this.isReady = false;
    await this.construction;
    this.#observers.close();
  }
  #syncOnlineStatus() {
    let shouldBeOnline;
    if (!this.#isReady) {
      shouldBeOnline = false;
    } else {
      const peer = this.owner.env.maybeGet(Peer);
      if (peer === void 0) {
        shouldBeOnline = false;
      } else {
        shouldBeOnline = peer.hasSession;
      }
    }
    if (this.owner.lifecycle.isOnline === shouldBeOnline) {
      return;
    }
    this.owner.act(({ context }) => {
      this.owner.lifecycle[shouldBeOnline ? "online" : "offline"].emit(context);
    });
  }
}
export {
  ClientNetworkRuntime,
  OfflineError,
  UncommissionedError
};
//# sourceMappingURL=ClientNetworkRuntime.js.map
