import React, { Component } from 'react'
import { OverlayTrigger, Tooltip, Glyphicon } from 'react-bootstrap'
import { TableSorter, TableSortType } from './data'

class NestedTableCol extends Component {

  constructor (props) {
    super(props)
    this.onToggleSort = this.onToggleSort.bind(this)
  }

  onToggleSort () {
    let sorter = this.props.sorter
    if (sorter === null || sorter.id !== this.props.id) {
      sorter = new TableSorter(this.props.id, TableSortType.ASCENDING)
    } else if (sorter.type === TableSortType.ASCENDING) {
      sorter = new TableSorter(this.props.id, TableSortType.DESCENDING)
    } else if (sorter.type === TableSortType.DESCENDING) {
      sorter = null
    }
    this.props.onToggleSort(sorter)
  }

  render () {
    let glyphImg = 'sort-by-attributes'
    let glyphLeft = <Glyphicon glyph={glyphImg} className='header-glyph left' />
    let glyphRightStyle = 'header-glyph right'
    let styleClassName = 'metrics-header'
    const sorter = this.props.sorter
    if (sorter !== null && sorter.id === this.props.id) {
      styleClassName += ' sorting'
      if (sorter.type === TableSortType.DESCENDING) {
        glyphImg = 'sort-by-attributes-alt'
      }
      glyphRightStyle += ' sorting'
    }
    let glyphRight = <Glyphicon glyph={glyphImg} className={glyphRightStyle} />
    const tooltip = (<Tooltip id='tooltip'>{this.props.tooltip}</Tooltip>)
    return (
      <th className={`text-center ${styleClassName}`}>
        <OverlayTrigger placement='top' overlay={tooltip}>
          <a className={styleClassName} onClick={this.onToggleSort}>
            {glyphLeft}
            {this.props.children}
            {glyphRight}
          </a>
        </OverlayTrigger>
      </th>
    )
  }
}

NestedTableCol.propTypes = {
  id: React.PropTypes.string.isRequired,
  tooltip: React.PropTypes.string,
  children: React.PropTypes.any,
  sorter: React.PropTypes.instanceOf(TableSorter),
  onToggleSort: React.PropTypes.func.isRequired
}

export default NestedTableCol
