"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 EventDataDecoder_exports = {};
__export(EventDataDecoder_exports, {
  decodeUnknownEventValue: () => decodeUnknownEventValue,
  normalizeAndDecodeEventData: () => normalizeAndDecodeEventData,
  normalizeAndDecodeReadEventReport: () => normalizeAndDecodeReadEventReport,
  normalizeEventData: () => normalizeEventData,
  normalizeEventStatus: () => normalizeEventStatus
});
module.exports = __toCommonJS(EventDataDecoder_exports);
var import_general = require("#general");
var import_types = require("#types");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const logger = import_general.Logger.get("EventDataDecoder");
function normalizeAndDecodeReadEventReport(data) {
  const dataValues = data.flatMap(({ eventData }) => eventData !== void 0 ? eventData : []);
  const dataStatus = data.flatMap(({ eventStatus }) => eventStatus !== void 0 ? eventStatus : []);
  return {
    eventData: normalizeAndDecodeEventData(dataValues),
    eventStatus: normalizeEventStatus(dataStatus)
  };
}
function normalizeEventData(data) {
  const responseList = /* @__PURE__ */ new Map();
  data.forEach((value) => {
    if (!value) return;
    const {
      path: { nodeId, endpointId, clusterId, eventId }
    } = value;
    const mapId = `${nodeId}-${endpointId}-${clusterId}-${eventId}`;
    const list = responseList.get(mapId) || [];
    list.push(value);
    responseList.set(mapId, list);
  });
  return Array.from(responseList.values());
}
function normalizeAndDecodeEventData(data) {
  const responseList = normalizeEventData(data);
  const result = new Array();
  responseList.forEach((values) => {
    const {
      path: { nodeId, endpointId, clusterId, eventId }
    } = values[0];
    if (endpointId === void 0 || clusterId === void 0 || eventId === void 0) {
      throw new import_general.UnexpectedDataError(`Invalid event path ${endpointId}/${clusterId}/${eventId}`);
    }
    try {
      const cluster = (0, import_types.getClusterById)(clusterId);
      const eventDetail = (0, import_types.getClusterEventById)(cluster, eventId);
      if (eventDetail === void 0) {
        logger.debug(
          `Decode unknown event ${import_general.Diagnostic.hex(clusterId)}/${import_general.Diagnostic.hex(eventId)} via the AnySchema.`
        );
        const eventName = `Unknown (${import_general.Diagnostic.hex(eventId)})`;
        const events2 = values.map((eventData) => ({
          ...eventData,
          data: eventData.data === void 0 ? void 0 : decodeUnknownEventValue(eventData.data),
          path: void 0
        }));
        result.push({ path: { nodeId, endpointId, clusterId, eventId, eventName }, events: events2 });
        return;
      }
      const {
        event: { schema },
        name
      } = eventDetail;
      const events = values.map((eventData) => ({
        ...eventData,
        data: eventData.data === void 0 ? void 0 : schema.decodeTlv(eventData.data),
        path: void 0
      }));
      result.push({ path: { nodeId, endpointId, clusterId, eventId, eventName: name }, events });
    } catch (error) {
      logger.error(`Error decoding event ${endpointId}/${clusterId}/${eventId}: ${error.message}`);
    }
  });
  return result;
}
function normalizeEventStatus(data) {
  const result = new Array();
  data.forEach((entry) => {
    const {
      path: { nodeId, endpointId, clusterId, eventId },
      status
    } = entry;
    if (endpointId === void 0 || clusterId === void 0 || eventId === void 0) {
      throw new import_general.UnexpectedDataError(`Invalid event path ${endpointId}/${clusterId}/${eventId}`);
    }
    try {
      const cluster = (0, import_types.getClusterById)(clusterId);
      const eventDetail = (0, import_types.getClusterEventById)(cluster, eventId);
      if (eventDetail === void 0) {
        result.push({
          path: { nodeId, endpointId, clusterId, eventId, eventName: `Unknown (${import_general.Diagnostic.hex(eventId)})` },
          status: status.status,
          clusterStatus: status.clusterStatus
        });
        return;
      }
      result.push({
        path: { nodeId, endpointId, clusterId, eventId, eventName: eventDetail.name },
        status: status.status,
        clusterStatus: status.clusterStatus
      });
    } catch (error) {
      logger.error(`Error decoding event ${endpointId}/${clusterId}/${eventId}: ${error.message}`);
    }
  });
  return result;
}
function decodeUnknownEventValue(data) {
  const schema = import_types.TlvAny;
  if (data.length === 0) {
    return void 0;
  }
  const tlvEncoded = schema.decodeTlv(data);
  return schema.decodeAnyTlvStream(tlvEncoded);
}
//# sourceMappingURL=EventDataDecoder.js.map
