"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 ClientEventEmitter_exports = {};
__export(ClientEventEmitter_exports, {
  ClientEventEmitter: () => ClientEventEmitter
});
module.exports = __toCommonJS(ClientEventEmitter_exports);
var import_NetworkClient = require("#behavior/system/network/NetworkClient.js");
var import_ChangeNotificationService = require("#node/integration/ChangeNotificationService.js");
var import_general = require("@matter/general");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const logger = import_general.Logger.get("ClientEventEmitter");
const nameCache = /* @__PURE__ */ new WeakMap();
const warnedForUnknown = /* @__PURE__ */ new Set();
function ClientEventEmitter(node, structure) {
  const changes = node.env.get(import_ChangeNotificationService.ChangeNotificationService);
  return emitClientEvent;
  async function emitClientEvent(occurrence) {
    const names = getNames(node.matter, occurrence);
    if (!names) {
      return;
    }
    const target = getTarget(node, occurrence, names.cluster, names.event);
    if (!target) {
      return;
    }
    await node.act(async (agent) => {
      target.event.emit(occurrence.value, agent.context);
      const network = agent.get(import_NetworkClient.NetworkClient);
      if (occurrence.number > network.state.maxEventNumber) {
        await agent.context.transaction.addResources(network);
        await agent.context.transaction.begin();
        network.state.maxEventNumber = occurrence.number;
        await agent.context.transaction.commit();
      }
    });
    const behavior = target.endpoint.behaviors.supported[names.cluster];
    if (behavior) {
      const { number, timestamp, priority, value } = occurrence;
      changes.broadcastEvent(target.endpoint, behavior, target.event.schema, {
        number,
        timestamp,
        priority,
        payload: value
      });
    }
  }
  function getTarget(node2, occurrence, clusterName, eventName) {
    const {
      value,
      path: { endpointId }
    } = occurrence;
    const endpoint = structure.endpointFor(endpointId);
    if (endpoint === void 0) {
      logger.warn(`Received event for unknown endpoint #${endpointId} on ${node2}`);
      return;
    }
    const events = endpoint.events[clusterName];
    if (events === void 0) {
      logger.warn(`Received event ${eventName} for unsupported cluster ${clusterName} on ${endpoint}`);
      return;
    }
    const event = events[eventName];
    if (event) {
      logger.info(
        "Received event",
        import_general.Diagnostic.strong(`${clusterName}.${eventName}`),
        " on ",
        import_general.Diagnostic.strong(endpoint.toString()),
        import_general.Diagnostic.weak((0, import_general.isObject)(value) ? import_general.Diagnostic.dict(value) : value)
      );
      return { endpoint, event };
    }
    logger.warn(`Received unknown event ${clusterName}.${eventName} on ${endpoint}`);
  }
}
function getNames(matter, { path: { clusterId, eventId } }) {
  let matterCache = nameCache.get(matter);
  if (matterCache === void 0) {
    matterCache = {};
    nameCache.set(matter, matterCache);
  }
  const key = `${clusterId}-${eventId}`;
  if (key in matterCache) {
    return matterCache[key];
  }
  const cluster = matter.clusters(clusterId);
  if (cluster === void 0) {
    if (!warnedForUnknown.has(clusterId)) {
      logger.notice(`Ignoring events for unknown cluster #${clusterId}`);
      warnedForUnknown.add(clusterId);
      matterCache[key] = void 0;
    }
    return;
  }
  const event = cluster.events(eventId);
  if (event === void 0) {
    if (!warnedForUnknown.has(key)) {
      logger.notice(`Ignoring unknown event #${eventId} for ${cluster.name} cluster`);
      warnedForUnknown.add(key);
      matterCache[key] = void 0;
    }
    return;
  }
  return matterCache[key] = { cluster: cluster.propertyName, event: event.propertyName };
}
//# sourceMappingURL=ClientEventEmitter.js.map
