/**
 * Component that's a clickable button to download the contents of a chart as
 *   a CSV file
 * @author Jackson Parsells
 * @author Gabe Abrams
 */
// Import react
import React from 'react';

// CSV lib
import Papa from 'papaparse';

// Import FontAwesome
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faDownload } from '@fortawesome/free-solid-svg-icons';

/*------------------------------------------------------------------------*/
/*                                  Types                                 */
/*------------------------------------------------------------------------*/

// props definition
type Props = {
  // Title of the chart
  title: string,
  // Chart Data for papa parse
  //  each string key corresponds to a string or number value, if it's a string
  //  it will be a column header, if it's a number it will be a value in that
  //  column
  chartData: {
    [k: string]: string | number
  }[],
  // filename to save the CSV as
  filename: string,
};

/*------------------------------------------------------------------------*/
/*                                Component                               */
/*------------------------------------------------------------------------*/

const DownloadButton: React.FC<Props> = (props: Props) => {
  /*------------------------------------------------------------------------*/
  /*                                  Setup                                 */
  /*------------------------------------------------------------------------*/

  /* -------------- Props ------------- */

  // destructure props
  const {
    title,
    chartData,
    filename,
  } = props;

  /*------------------------------------------------------------------------*/
  /*                                 Render                                 */
  /*------------------------------------------------------------------------*/

  /*----------------------------------------*/
  /*                 Main UI                */
  /*----------------------------------------*/

  // Generate CSV text
  const csvText = Papa.unparse(chartData);

  // Download button
  return (
    <a
      href={`data:text/csv;charset=utf-8,${encodeURI(csvText)}`}
      download={filename}
      className="btn btn-sm btn-primary"
      style={{
        borderTopLeftRadius: 0,
        borderBottomRightRadius: 0,
      }}
      title="Download Data as CSV"
      aria-label={`download the data of ${title} as a csv file`}
    >
      <FontAwesomeIcon
        icon={faDownload}
      />
    </a>
  );
};

export default DownloadButton;
