import O from "lodash/find";
function b(a) {
  return typeof a == "string" ? a.replace(/^\+|^\-|^\=|^\@/g, "'$&") : a;
}
function h(a, i, r) {
  const l = (t) => typeof t == "string" ? t.replace(/"/g, '""') : t, o = (t) => `${t.reduce(
    (e, d) => d.download ? `${e}"${b(l(d.label || d.name))}"${r.downloadOptions.separator}` : e,
    ""
  ).slice(0, -1)}\r
`, p = o(a), n = (t) => t.length ? t.reduce(
    (e, d) => `${e}"${d.data.filter((s, f) => a[f].download).map((s) => b(l(s))).join(`"${r.downloadOptions.separator}"`)}"\r
`,
    ""
  ).trim() : "", u = n(i);
  return r.onDownload ? r.onDownload(o, n, a, i) : `${p}${u}`.trim();
}
function m(a, i) {
  const r = new Blob([a], { type: "text/csv" });
  if (navigator && navigator.msSaveOrOpenBlob)
    navigator.msSaveOrOpenBlob(r, i);
  else {
    const l = `data:text/csv;charset=utf-8,${a}`, o = window.URL || window.webkitURL, p = typeof o.createObjectURL > "u" ? l : o.createObjectURL(r), n = document.createElement("a");
    n.setAttribute("href", p), n.setAttribute("download", i), document.body.appendChild(n), n.click(), document.body.removeChild(n);
  }
}
function x(a, i, r, l) {
  const o = h(a, i, r);
  r.onDownload && o === !1 || l(o, r.downloadOptions.filename);
}
function C(a) {
  const { data: i, displayData: r, columns: l, options: o, columnOrder: p } = a;
  let n = [], u = [], c = Array.isArray(p) ? p.slice(0) : [];
  if (c.length === 0 && (c = l.map((t, e) => e)), i.forEach((t) => {
    const e = { index: t.index, data: [] };
    c.forEach((d) => {
      e.data.push(t.data[d]);
    }), n.push(e);
  }), c.forEach((t) => {
    u.push(l[t]);
  }), o.downloadOptions && o.downloadOptions.filterOptions) {
    if (o.downloadOptions.filterOptions.useDisplayedRowsOnly) {
      const t = r.map((e, d) => {
        let s = -1;
        return e.index = d, {
          data: e.data.map((f) => {
            s += 1;
            let w = typeof f == "object" && f !== null && !Array.isArray(f) ? O(i, (y) => y.index === e.dataIndex).data[s] : f;
            return w = typeof w == "function" ? O(i, (y) => y.index === e.dataIndex).data[s] : w, w;
          })
        };
      });
      n = [], t.forEach((e) => {
        const d = { index: e.index, data: [] };
        c.forEach((s) => {
          d.data.push(e.data[s]);
        }), n.push(d);
      });
    }
    o.downloadOptions.filterOptions.useDisplayedColumnsOnly && (u = u.filter((t) => t.display === "true"), n = n.map((t) => (t.data = t.data.filter((e, d) => l[c[d]].display === "true"), t)));
  }
  x(u, n, o, m);
}
const v = { handleCSVDownload: C };
export {
  v as default,
  C as handleCSVDownload
};
