import * as React from 'react';
import { Tips } from "./Utils";
import * as _ from 'lodash';
import { Button } from 'bloomer';
const randomColor = require('randomcolor');
const reactcsv = require('react-csv');
const CSVLink = reactcsv.CSVLink;
import * as Papa from 'papaparse';

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

export default class ServerTable extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      headers: [], data: [], colColorMap: {}
    }
    const loaded = (results: any) => {
      const local = this;
      const colsUnique = _.keys(_.groupBy(results.data, (o: any) => _.get<any>(o, this.props.colorColumn)));
      const colColorMap = _.zipObject(colsUnique, _.map(colsUnique, () => randomColor()));
      local.setState({
        headers: results.meta.fields,
        data: results.data,
        colColorMap
      });
    }
    Papa.parse(this.props.csvFile, {
      header: true,
      download: true,
      skipEmptyLines: true,
      dynamicTyping: true,
      complete: loaded
    });
  }

  public render() {
    const data = this.state.data;
    const headers = this.state.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: headerName,
        accessor: headerName,
        Cell: (row: any) => {
          return row.value;
        }
      }
    }
    const colorCol = this.props.colorColumn;
    const colColorMap = this.state.colColorMap;
    const rowStyle = (_0: any, rowInfo: any, _1: any) => {
      if (_.isUndefined(rowInfo) || _.isUndefined(colorCol)) {
        return {};
      }
      const colValue = _.get<any>(rowInfo.row, colorCol, '');
      const colColor = _.get<any>(colColorMap, colValue, 'green');
      return {
        style: {
          background: colColor
        }
      };
    };
    const headerCols = headers.map(headerGen);
    return (
      <ReactTable
        data={data}
        filterable={true}
        defaultFilterMethod={filterPart}
        columns={headerCols}
        showPagination={false}
        defaultPageSize={100}
        className="-striped -highlight"
        getTrProps={rowStyle}
        style={{
          height: "75vh"
        }}
      >
        {(state, makeTable, ) => {
          const lastFiltered = state.sortedData.map((o: any) => _.pick(o, headers));
          return (
            <div>
              {makeTable()}
              {/* <Chart data={lastFiltered} /> */}
              <Button>
                <CSVLink data={lastFiltered} filename={"data.csv"}>
                  Download CSV
                </CSVLink>
              </Button>
              <br />
              <Tips />
            </div>
          )
        }}
      </ReactTable>

    );
  }

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