import * as React from 'react';
import { Tips, Logo } from "./Utils";
import * as Papa from 'papaparse';
const reactcsv = require('react-csv');
const CSVLink = reactcsv.CSVLink;

// Import React Table
import ReactTable from 'react-table';
import "react-table/react-table.css";

export class ServerTable extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      headers: [],
      data: []
    };
    this.loaded = this.loaded.bind(this);
    Papa.parse('/data.csv', {
      header: true,
      download: true,
      skipEmptyLines: true,
      complete: this.loaded
    });
  }

  public render() {
    const { data, headers } = this.state;
    const filterPart = (filter: any, row: any) =>
      row[filter.id].startsWith(filter.value) ||
      row[filter.id].endsWith(filter.value)
    const headerGen = (headerName: string) => {
      const title = headerName.replace(/([A-Z])/g, ' $1').replace(/^./, (str:string) => str.toUpperCase());
      return {
        Header: title,
        accessor: headerName
      }
    }
    const headerCols = headers.map(headerGen);
    return (
      <div>
        <ReactTable
          data={data}
          filterable={true}
          defaultFilterMethod={filterPart}
          columns={headerCols}
          defaultPageSize={20}
          className="-striped -highlight"
        />
        <br />
        <CSVLink data={data} filename={"data.csv"}>Click here to download CSV file</CSVLink>
        <Tips />
        <Logo />
      </div>
    );
  }

  public loaded(results: any) {
    this.setState({
      headers: results.meta.fields,
      data: results.data
    });
  }
}
