import { getOrders } from '../api/Orders';
import { getPart } from '../api/Parts';
import { getRequests } from '../api/Requests';
import { getTeam } from '../api/Teams';

export const ExportData = async () => {
  // Empty array for storing each request within an order
  let csvRows = [];
  const headers = [
    'order_id',
    'request_num',
    'request_timestamp',
    'section_num',
    'part_name',
    'part_url',
    'part_price',
    'quantity',
    'subtotal',
  ];
  csvRows.push(headers.join(','));

  try {
    const orders = await getOrders();
    for (const order of orders) {
      // Get requests by order for each iteration
      const requests = await getRequests(
        undefined,
        undefined,
        undefined,
        undefined,
        order.order_id,
        undefined
      );

      let request_num = 0;
      for (const request of requests) {
        request_num += 1;
        let team = await getTeam(request.team_id);
        let part = await getPart(request.part_id);

        let row = [
          `"${order.order_id}"`,
          `"${request_num}"`,
          `"${request.request_timestamp}"`,
          `"${team.section_id}"`,
          `"${part.description.slice(0, 30)}"`,
          `"${part.url}"`,
          `"${part.price}"`,
          `"${request.quantity}"`,
          `"${request.subtotal}"`,
        ].join(',');

        csvRows.push('\n' + row);
      }
    }

    // Date info for filename
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1; // Month is 0-indexed, so add 1
    const day = now.getDate();
    const filename = `ShipME ${year}-${month}-${day}`;

    // Download the CSV file
    download(csvRows, filename);
  } catch (error) {
    throw new Error('Failed to export application data: ' + error);
  }
};

function download(csvRows: any, filename: string) {
  // Create a Blob with CSV content
  csvRows.join('');
  const blob = new Blob([csvRows], { type: 'text/csv;charset=utf-8;' });

  // Create a temporary link element
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', filename);

  // Append to the DOM and trigger download
  document.body.appendChild(link);
  link.click();

  // Cleanup
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}
