// Copyright (c) 2017 PlanGrid, Inc.

import React, { Component } from 'react';
import { OutTable } from 'react-excel-renderer';
import XLSX from 'xlsx';
import 'styles/csv.scss';

export function makeCols(refstr) {
  let o = [],
    C = XLSX.utils.decode_range(refstr).e.c + 1;
  for (let i = 0; i <= C; i += 1) {
    if (i === 0) o[i] = { name: '', key: i };
    else o[i] = { name: XLSX.utils.encode_col(i - 1), key: i };
  }
  return o;
}

class CsvViewer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rows: [],
      columns: [],
      sheetCollection: [],
      activeSheetIndex: 0
    };
  }

  componentDidMount() {
    this.setSheet();
  }

  componentWillReceiveProps(nextProps) {
    this.setSheet(0, nextProps.data);
  }

  setSheet(sheetIndex = 0, file = this.props.data, callback = () => {}) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      const rABS = !!reader.readAsBinaryString;
      reader.onload = (e) => {
        /* Parse data */
        const bstr = e.target.result;
        const wb = XLSX.read(bstr, { type: rABS ? 'binary' : 'array' });

        /* Get first worksheet */
        const wsname = wb.SheetNames[sheetIndex];
        const ws = wb.Sheets[wsname];

        /* Convert array of arrays */
        const json = XLSX.utils.sheet_to_json(ws, { header: 1 });
        const cols = makeCols(ws['!ref']);

        const data = { rows: json, cols };

        this.setState({
          rows: json,
          columns: cols,
          sheetCollection: wb.SheetNames,
          activeSheetIndex: sheetIndex
        });

        resolve(data);
        return callback(null, data);
      };
      if (file && rABS) reader.readAsBinaryString(file);
      else reader.readAsArrayBuffer(file);
    });
  }

  handleSheetChange(sheetIndex) {
    this.setSheet(sheetIndex);
  }

  render() {
    const { rows, columns, sheetCollection, activeSheetIndex } = this.state;
    return (
      <div className="csv__container">
        {sheetCollection.map((item, i) => (
          <button
            key={`${item}-${i.toString}`}
            className={`csv__button ${activeSheetIndex === i ? 'csv__button--active' : ''}`}
            onClick={() => this.handleSheetChange(i)}
          >
            <p>{item}</p>
          </button>
        ))}
        <div id="table-container" className="csv__table-container">
          <OutTable
            data={rows}
            columns={columns}
            tableClassName="ExcelTable2007"
            tableHeaderRowClass="heading"
          />
        </div>
      </div>
    );
  }
}

export default CsvViewer;
