"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 RemoteWriter_exports = {};
__export(RemoteWriter_exports, {
  RemoteWriter: () => RemoteWriter
});
module.exports = __toCommonJS(RemoteWriter_exports);
var import_general = require("@matter/general");
var import_protocol = require("@matter/protocol");
var import_types = require("@matter/types");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const attrCache = /* @__PURE__ */ new WeakMap();
function RemoteWriter(node, structure) {
  return async function writeRemote(request, onFailure) {
    const attrWrites = Array();
    for (const { number, behaviorId, values } of request) {
      const cluster = structure.clusterFor(number, Number.parseInt(behaviorId));
      if (cluster === void 0) {
        throw new import_general.InternalError(`Cannot remote write to non-cluster behavior ${behaviorId}`);
      }
      const attrs = attrsFor(cluster);
      for (const id in values) {
        const attr = attrs[id];
        if (attr === void 0) {
          if (id.startsWith("__")) {
            continue;
          }
          throw new import_general.InternalError(`Cannot write unknown attribute ${id} for ${behaviorId}`);
        }
        attrWrites.push(
          import_protocol.Write.Attribute({
            endpoint: number,
            cluster,
            attributes: [attrs[id]],
            value: values[id]
          })
        );
      }
    }
    const write = (0, import_protocol.Write)(...attrWrites);
    const result = await node.interaction.write(write);
    if (onFailure) {
      const failures = result.filter((s) => s.status !== import_types.Status.Success);
      if (failures.length) {
        await onFailure(failures);
      }
    }
    import_protocol.WriteResult.assertSuccess(result);
  };
}
function attrsFor(cluster) {
  let attrs = attrCache.get(cluster);
  if (attrs) {
    return attrs;
  }
  const nsAttrs = cluster.attributes;
  attrs = {};
  if (nsAttrs) {
    for (const attr of Object.values(nsAttrs)) {
      attrs[attr.id] = attr;
    }
  }
  attrCache.set(cluster, attrs);
  return attrs;
}
//# sourceMappingURL=RemoteWriter.js.map
