import dayjs from 'dayjs';
import timezonePlugin from 'dayjs/plugin/timezone';
import utcPlugin from 'dayjs/plugin/utc';

dayjs.extend(utcPlugin);
dayjs.extend(timezonePlugin);

export const createTotal = ({ users, totalMinutes, averageMinutes, averageMinutesPercent }) => {
  const head = ['Users', 'Total viewed minutes', 'Average viewed minutes', 'Average viewed minutes(percent)'];

  const body = [users, totalMinutes, averageMinutes, averageMinutesPercent];

  const rows = [head, body];

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

  return csvContent;
};

export const createDevices = ({ desktop, mobile }) => {
  const head = ['Resolution', 'Desktop', 'Mobile'];

  const body = [
    ['All', desktop.all, mobile.all],
    ['X Large', desktop.xLarge, '-'],
    ['Large', desktop.large, '-'],
    ['Medium & Smaller', desktop.medium, '-'],
    ['Medium', '-', mobile.medium],
    ['Small', '-', mobile.small],
    ['X Small', '-', mobile.xSmall],
  ];

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

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

  return csvContent;
};

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

  const body = [['All Countries', all, '100%']];
  items.forEach(({ name, value, percent }) => {
    body.push([`"${name.replace(/"/g, "'")}"`, value, `${percent}%`]);
  });

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

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

  return csvContent;
};

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

  const body = [];
  chartData.forEach(({ name, data }, index) => {
    head.push(name);
    data.forEach(({ time, value }) => {
      const timeValue = dayjs(time).tz(userTimezone);
      const rowValues = Array.from({ length: chartData.length }, (_, i) => {
        if (i === index) {
          return value;
        }
        return '';
      });
      body.push([`"${time === '' ? 'Break' : timeValue.format('HH:mm MMM DD')}"`, ...rowValues]);
    });
  });

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

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

  return csvContent;
};
