/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { Subject } from "#action/server/Subject.js";
import { BasicMap, DataWriter, ImplementationError, ipv6BytesToString } from "@matter/general";
import { GroupId } from "@matter/types";
class Groups {
  #fabric;
  #keySets;
  /** Operational variant of the group key map attribute from Group Key Management cluster, maps group Ids to key sets. */
  #groupKeyIdMap = new BasicMap();
  /** Operational variant of the group table, maps group Ids to a list of enabled endpoints. */
  endpointMap = /* @__PURE__ */ new Map();
  constructor(fabric, keySets) {
    this.#fabric = fabric;
    this.#keySets = keySets;
  }
  /** Operative lookup of the group key sets by a group id and to react on added removed groups. */
  get idMap() {
    return this.#groupKeyIdMap;
  }
  /** Updates the group key id map when changed in Group Key Management Cluster. Only changes are taken over. */
  set idMap(map) {
    for (const [groupId, keySetId] of map.entries()) {
      this.#groupKeyIdMap.set(groupId, keySetId);
    }
    for (const groupId of this.#groupKeyIdMap.keys()) {
      if (!map.has(groupId)) {
        this.#groupKeyIdMap.delete(groupId);
      }
    }
  }
  subjectForGroup(id, keySetId) {
    return Subject.Group({
      id,
      hasValidMapping: this.idMap.get(id) === keySetId,
      endpoints: this.endpointMap.get(id) ?? []
    });
  }
  /** Returns the multicast address for a given group id for this fabric. */
  multicastAddress(groupId) {
    GroupId.assertGroupId(groupId);
    const writer = new DataWriter();
    writer.writeUInt16(65333);
    writer.writeUInt16(64);
    writer.writeUInt8(253);
    writer.writeUInt64(this.#fabric.fabricId);
    writer.writeUInt8(0);
    writer.writeUInt16(GroupId(groupId));
    return ipv6BytesToString(writer.toByteArray());
  }
  /**
   * Returns the current operational group key for a given group id and returns the keys, start time and
   * their session IDs.
   */
  currentKeyForId(groupId) {
    const keySetId = this.#groupKeyIdMap.get(groupId);
    if (keySetId === void 0) {
      throw new ImplementationError(`No group key set found for groupId ${groupId}.`);
    }
    return { ...this.#keySets.currentKeyForId(keySetId), keySetId };
  }
}
export {
  Groups
};
//# sourceMappingURL=Groups.js.map
