import { isObject, isUndefined } from "lodash-es";
import { _accessValue as accessValue } from "@dynatrace/strato-components-preview/core";
const NESTED_LEVELS_SUPPORTED = 2;
const buildColumnsHeadersMapping = (columns) => new Map([...columns].map((value, index) => [value, index]));
const getObjectHeaders = (data, objectKey = "", nestingLevel = 0) => {
  let columnHeaders = [];
  if (nestingLevel <= NESTED_LEVELS_SUPPORTED) {
    for (let i = 0; i < data.length; i++) {
      for (const [key, value] of Object.entries(data[i])) {
        const objectPath = [objectKey, key].filter((a) => a).join(".");
        if (!isObject(value)) {
          columnHeaders.push(objectPath);
        } else if (!Array.isArray(value)) {
          const headers = getObjectHeaders(
            [value],
            objectPath,
            nestingLevel + 1
          );
          columnHeaders = columnHeaders.concat(headers);
        }
      }
    }
  }
  return columnHeaders;
};
const getColumnHeaders = (data) => {
  const objectColumnHeaders = getObjectHeaders(data);
  const columnHeadersSet = new Set(objectColumnHeaders);
  const sortedHeaders = ["layer-name", "latitude", "longitude"];
  const startingHeaders = sortedHeaders.reduce(
    (headersList, column) => {
      if (columnHeadersSet.has(column)) {
        headersList.push(column);
      }
      return headersList;
    },
    []
  );
  return /* @__PURE__ */ new Set([...startingHeaders, ...objectColumnHeaders]);
};
const tabularizeLayersData = (data) => {
  let csv = "";
  if (data.length > 0) {
    const columnHeaders = getColumnHeaders(data);
    csv += `${[...columnHeaders].join(",")}
`;
    const columnCount = columnHeaders.size;
    const headersMapping = buildColumnsHeadersMapping(columnHeaders);
    for (const datum of data) {
      const row = [];
      row.length = columnCount;
      for (const [column, index] of headersMapping) {
        let value = accessValue(datum, column);
        if (!isUndefined(value)) {
          if (typeof value === "string" && value.includes(",")) {
            value = `"${value}"`;
          }
          row[index] = value;
        }
      }
      csv += `${row.join(",")}
`;
    }
  }
  return csv;
};
export {
  getColumnHeaders,
  tabularizeLayersData
};
//# sourceMappingURL=tabularize-layers-data.js.map
