var formatValue = function formatValue(value) {
  if (value === null || value === undefined) return "-";
  if (typeof value === "object") return JSON.stringify(value);
  return value;
};
var escapeForCSV = function escapeForCSV(value) {
  var str = String(value);
  if (/[",\n\r]/.test(str)) return "\"" + str.replace(/"/g, '""') + "\"";
  return str;
};
var convertToCSV = function convertToCSV(data) {
  return data.reduce(function (h, row) {
    return h + row.map(function (v) {
      return escapeForCSV(formatValue(v));
    }).join(",") + "\n";
  }, "");
};
export default (function (name) {
  if (name === void 0) {
    name = "netdata";
  }
  return function (_, table) {
    var headers = table.getFlatHeaders().filter(function (header) {
      var _header$subHeaders;
      return !((_header$subHeaders = header.subHeaders) != null && _header$subHeaders.length) && header.id !== "checkbox" && header.id !== "actions";
    });
    var data = [headers.map(function (header) {
      var parentLabel = header.column.parent ? typeof header.column.parent.columnDef.headerString === "function" ? header.column.parent.columnDef.headerString() : header.column.parent.id : null;
      var label = typeof header.column.columnDef.headerString === "function" ? header.column.columnDef.headerString() : header.id;
      return parentLabel ? parentLabel + " " + label : label;
    })];
    table.getRowModel().rows.forEach(function (row) {
      return data.push(headers.map(function (header) {
        var value = row.getValue(header.id);
        if (value) return value;
        if (typeof header.column.columnDef.renderString !== "function") return value;
        var cell = row.getAllCells().find(function (cell) {
          return cell.column.id === header.id;
        });
        return header.column.columnDef.renderString(cell.row);
      }));
    });
    var url = window.URL.createObjectURL(new Blob([convertToCSV(data)], {
      type: "text/csv;charset=utf-8;"
    }));
    var link = document.createElement("a");
    link.href = url;
    var fileName = name + ".csv";
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    link.remove();
  };
});