import * as React from 'react';
import { Tips } from "./Utils";
import * as _ from 'lodash';
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> {
  private lastFiltered: any[] = []
  constructor(props: any) {
    super(props);
  }

  public render() {
    const data = this.props.data;
    const headers = this.props.headers;
    const filterPart = (filter: any, row: any) =>
      String(row[filter.id]).startsWith(filter.value) ||
      String(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
      }
    }
    debugger;
    const headerCols = headers.map(headerGen);
    return (
      <ReactTable
        data={data}
        filterable={true}
        defaultFilterMethod={filterPart}
        columns={headerCols}
        defaultPageSize={20}
        className="-striped -highlight"
        style={{
          height: "450px"
        }}
      >
        {(state, makeTable,) => {
          this.lastFiltered = state.sortedData.map((o: any) => _.pick(o, headers));
          return (
            <div>
              {makeTable()}
              <CSVLink data={this.lastFiltered} filename={"data.csv"}>
                Click here to download CSV file
              </CSVLink>
              <br />
              <Tips />
            </div>
          )
        }}
      </ReactTable>

    );
  }

  public componentWillUnmount() {
    this.props.setData(this.lastFiltered);
  }

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