import React, { Component } from 'react'
import { Collapse, Well } from 'react-bootstrap'
const enhanceWithClickOutside = require('react-click-outside')
import ToggleCol from './ToggleCol'
import ToggleRow from './ToggleRow'
import ToggleEntry from './ToggleEntry'
import './ToggleTable.scss'

class ToggleTable extends Component {

  /**
   * This is used to handle toggling the visiblity of our TouggleTable, if a click happened outside of the table.
   * Parent component will need to handle the visiblity accordingly by defining onClickOutside.
   */
  handleClickOutside () {
    if (this.props.onClickOutside !== undefined) {
      this.props.onClickOutside(this.props.hidden)
    }
  }

  render () {
    let cols = this.props.metrics.map((metric, idx) => {
      return <ToggleCol key={idx} metric={metric} onSelect={this.props.onSelect} />
    })
    let maxNumRowCols = 6
    let rowCols = []
    let tableRows = []
    cols.forEach((rowCol, idx) => {
      rowCols.push(rowCol)
      if (rowCols.length === maxNumRowCols) {
        tableRows.push(<ToggleRow key={idx} cols={rowCols} />)
        rowCols = []
      }
    })
    // If there's left-overs, then add the extra row.
    if (rowCols.length > 0) {
      tableRows.push(<ToggleRow key={tableRows.length - 1} cols={rowCols} />)
    }

    return (
      <Collapse in={!this.props.hidden}>
        <div>
          <div className='toggle-table-container'>
            <Well>
              <table className='toggle-table'>
                <tbody>
                  {tableRows}
                </tbody>
              </table>
            </Well>
          </div>
        </div>
      </Collapse>
    )
  }
}

ToggleTable.propTypes = {
  metrics: React.PropTypes.arrayOf(React.PropTypes.instanceOf(ToggleEntry)),
  hidden: React.PropTypes.bool,
  onSelect: React.PropTypes.func,
  onClickOutside: React.PropTypes.func
}

export default enhanceWithClickOutside(ToggleTable)
