"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 ClientNodeInteraction_exports = {};
__export(ClientNodeInteraction_exports, {
  ClientNodeInteraction: () => ClientNodeInteraction
});
module.exports = __toCommonJS(ClientNodeInteraction_exports);
var import_NetworkClient = require("#behavior/system/network/NetworkClient.js");
var import_EndpointInitializer = require("#endpoint/properties/EndpointInitializer.js");
var import_general = require("@matter/general");
var import_protocol = require("@matter/protocol");
var import_ClientNodePhysicalProperties = require("./ClientNodePhysicalProperties.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const logger = import_general.Logger.get("ClientNodeInteraction");
class ClientNodeInteraction {
  #node;
  #observers = new import_general.ObserverGroup();
  #interactable;
  #interactableClosed;
  constructor(node) {
    this.#node = node;
    this.#observers.on(
      this.#node.events.commissioning.peerAddress$Changed,
      () => this.#closeInteraction(new import_protocol.OperationalAddressChangedError())
    );
    this.#observers.on(this.#node.owner?.lifecycle.goingOffline, () => this.#closeInteraction(new import_protocol.ShutdownError()));
  }
  async close() {
    this.#observers.close();
    this.#closeInteraction(new import_protocol.ShutdownError());
    await this.#interactableClosed;
  }
  /**
   * Read chosen attributes remotely from the node. Known data versions are automatically injected into the request to
   * optimize the read when the fabric filter matches the active subscription. Set `includeKnownVersions` in the
   * request to skip version injection and always receive a full response from the server.
   */
  async *read(request, context) {
    if (!request.includeKnownVersions && (request.isFabricFiltered ?? true) === this.#structure.subscribedFabricFiltered) {
      request = this.#structure.injectVersionFilters(request);
    }
    const response = this.#interaction.read(request, context);
    yield* this.#structure.mutate(request, response);
  }
  /**
   * Subscribe to remote events and attributes as defined by {@link request}.
   *
   * matter.js updates local state
   *
   * By default, matter.js subscribes to all attributes and events of the peer and updates {@link ClientNode} state
   * automatically.  So you normally do not need to subscribe manually.
   *
   * When providing the "sustain" flag, a SustainedSubscription is returned immediately. You need to use the events to
   * know when/if a subscription could be established.  This class handles reconnections automatically.
   * When not providing the "sustain" flag, a PeerSubscription is returned after a subscription have been successfully
   * established; or an error is returned if this was not possible.
   */
  async subscribe(request, context) {
    const intermediateRequest = {
      ...this.#structure.injectVersionFilters(request),
      ...import_protocol.PhysicalDeviceProperties.subscriptionIntervalBoundsFor({
        description: this.#node.toString(),
        properties: (0, import_ClientNodePhysicalProperties.ClientNodePhysicalProperties)(this.#node),
        request
      }),
      sustain: !!request.sustain,
      updated: async (data) => {
        const result = this.#structure.mutate(request, data);
        if (request.updated) {
          await request.updated(result);
        } else {
          for await (const _chunk of result) ;
        }
      },
      refreshRequest: (request2) => {
        const updated = {
          ...request2,
          dataVersionFilters: void 0,
          eventFilters: [{ eventMin: this.#node.stateOf(import_NetworkClient.NetworkClient).maxEventNumber + 1n }]
        };
        return this.#structure.injectVersionFilters(updated);
      },
      closed: request.closed?.bind(request)
    };
    return this.#interaction.subscribe(intermediateRequest, context);
  }
  /**
   * Write chosen attributes remotely to the node.
   * The returned attribute write status information is returned.
   */
  async write(request, context) {
    return this.#interaction.write(request, context);
  }
  /**
   * Invoke a command remotely on the node.
   * The returned command response is returned as response chunks (attr-status).
   *
   * When the number of commands exceeds the peer's MaxPathsPerInvoke limit (or 1 for older nodes),
   * commands are split across multiple parallel exchanges automatically by ClientInteraction.
   *
   * Single commands may be automatically batched with other commands invoked in the same timer tick.
   */
  async *invoke(request, context) {
    if (request.network === void 0) {
      request.network = "unlimited";
    }
    yield* this.#interaction.invoke(request, context);
  }
  /**
   * Initiate a BDX Message Exchange with the node.
   *
   * The provided function is called with the established context to perform BDX operations.
   *
   * Request options may be omitted to use defaults.
   */
  async initBdx(request = {}, context) {
    return this.#interaction.initBdx(request, context);
  }
  async probe(options) {
    if (this.#node.construction.status !== import_general.Lifecycle.Status.Active || !this.#node.owner?.lifecycle.isOnline || this.#node.state.commissioning.peerAddress === void 0) {
      return false;
    }
    return this.#interaction.probe(options);
  }
  get subscriptions() {
    return this.#node.env.get(import_protocol.ClientSubscriptions);
  }
  get #interaction() {
    if (this.#node.construction.status !== import_general.Lifecycle.Status.Active) {
      throw new import_general.ImplementationError(
        `Cannot interact with ${this.#node} because it is ${this.#node.construction.status}`
      );
    }
    if (!this.#node.owner?.lifecycle.isOnline) {
      throw new import_general.ImplementationError(`Cannot interact with ${this.#node} because the local node is not online`);
    }
    if (this.#interactable) {
      return this.#interactable;
    }
    const address = this.#node.state.commissioning.peerAddress;
    if (address === void 0) {
      throw new import_general.ImplementationError(`Cannot interact with ${this.#node} because it is uncommissioned`);
    }
    const peer = this.#node.env.get(import_protocol.PeerSet).for(address);
    this.#interactable = new import_protocol.ClientInteraction({
      environment: this.#node.env,
      exchangeProvider: peer.exchangeProvider
    });
    return this.#interactable;
  }
  /**
   * Close currently open interaction.
   */
  #closeInteraction(reason) {
    if (!this.#interactable) {
      return;
    }
    const closed = this.#interactable.close(reason).catch((e) => {
      logger.warn(`Unhandled error closing client interaction`, e);
    });
    this.#interactable = void 0;
    if (this.#interactableClosed) {
      this.#interactableClosed = import_general.MatterAggregateError.allSettled([this.#interactableClosed, closed]);
    } else {
      this.#interactableClosed = closed;
    }
  }
  get #structure() {
    return this.#node.env.get(import_EndpointInitializer.EndpointInitializer).structure;
  }
  /**
   * Temporary accessor of cached data, if any are stored. This will be implemented by the ClientNodeInteraction and
   * point to the node state of the relevant endpoint and is needed to support the old API behavior for
   * AttributeClient.
   * TODO Remove when we remove the legacy controller API
   * @deprecated
   */
  localStateFor(endpointId) {
    if (!this.#node.endpoints.has(endpointId)) {
      return;
    }
    const endpoint = this.#node.endpoints.for(endpointId);
    return endpoint.state;
  }
}
//# sourceMappingURL=ClientNodeInteraction.js.map
