export const createTotal = ({ totals, cards }) => {
  const head = ['Name', 'Value', 'Percent'];

  const body = [];
  cards.forEach(({ title, key, postfix }) => {
    body.push([
      title,
      totals?.total?.[key]
        ? `"${Math.round((postfix ? totals.total[key] * 100 : totals.total[key]) * 100) / 100}"`
        : '',
      totals?.comparisonPct?.[`${key}Pct`] ? Math.round(totals.comparisonPct[`${key}Pct`] * 100) / 100 : '',
    ]);
  });

  const rows = [head, ...body];

  const csvContent = rows.map((e) => e.join(',')).join('\n');

  return csvContent;
};

export const createDevices = ({ devices }) => {
  const head = ['Device', 'Value', 'Percent'];

  const body = [];
  devices.forEach(({ device, value, valuePct }) => {
    body.push([`"${device.replace(/"/g, "'")}"`, Math.round(value * 100) / 100, Math.round(valuePct * 100) / 100]);
  });
  const rows = [head, ...body];

  const csvContent = rows.map((e) => e.join(',')).join('\n');

  return csvContent;
};

export const createCountries = ({ countries }) => {
  const head = ['Name', 'Percent'];

  const body = [];
  countries.forEach(({ name, valuePct }) => {
    body.push([`"${name.replace(/"/g, "'")}"`, Math.round(valuePct * 100) / 100]);
  });

  const rows = [head, ...body];

  const csvContent = rows.map((e) => e.join(',')).join('\n');

  return csvContent;
};

export const createChart = ({ chartData, activeCardFilter }) => {
  const head = ['Period'];

  const longestBuckets = chartData.reduce((acc, cur) => {
    if (cur?.buckets?.length > acc.length) {
      return cur.buckets;
    }

    return acc;
  }, []);

  const body = [];

  if (longestBuckets?.length) {
    longestBuckets.forEach((item) => {
      head.push(item.xTick);
    });

    chartData.forEach(({ chip, buckets }) => {
      const rowValues = Array.from({ length: longestBuckets.length }, (_, i) => {
        if (buckets[i]) {
          const value = buckets[i][activeCardFilter.key];

          return `"${Math.round((activeCardFilter?.postfix ? value * 100 : value) * 100) / 100}"`;
        }
        return '';
      });

      body.push([`"${chip}"`, ...rowValues]);
    });
  }

  const rows = [head, ...body];

  const csvContent = rows.map((e) => e.join(',')).join('\n');

  return csvContent;
};
