import React from 'react'
import { DropdownButton, MenuItem } from 'react-bootstrap'

class EnumDropdown extends React.Component {

  constructor (props) {
    super(props)
    let enums = []
    props.enum.enumValues.forEach((enumValue, idx) => {
      let name = enumValue.name.replace(/_/g, ' ').toLowerCase()
      name = name.split(' ').map(function (word) {
        return word.charAt(0).toUpperCase() + word.slice(1)
      }).join(' ')
      if (props.prefix !== undefined) {
        name = props.prefix + name
      }
      enums.push({ name: name, value: enumValue, idx: idx })
    })
    this.state = {
      enums: enums
    }
    this.handleSelect = this.handleSelect.bind(this)
    this.handleToggle = this.handleToggle.bind(this)
  }

  handleSelect (eventKey, event) {
    let enumValue = this.state.enums[eventKey].value
    this.props.onEnumSelect(enumValue)
  }

  handleToggle (isOpen) {
    if (this.props.onToggle !== undefined) {
      this.props.onToggle(isOpen)
    }
  }

  render () {
    const filter = this.props.filter
    let enums = this.state.enums
    if (filter !== undefined) {
      enums = enums.filter((enumObj) => {
        for (const filterEnum of filter) {
          if (enumObj.value === filterEnum) {
            return true
          }
        }
        return false
      })
    }

    let items = enums.map((enumValue, idx) => {
      return <MenuItem key={`${enumValue.idx}`} eventKey={`${enumValue.idx}`}>{enumValue.name}</MenuItem>
    })
    return (
      <DropdownButton
        disabled={this.props.disabled}
        title={this.props.title}
        id='bg-nested-dropdown'
        onSelect={this.handleSelect}
        onToggle={this.handleToggle}>
        {items}
      </DropdownButton>
    )
  }
}

EnumDropdown.propTypes = {
  enum: React.PropTypes.func,
  title: React.PropTypes.string,
  prefix: React.PropTypes.string,
  filter: React.PropTypes.arrayOf(React.PropTypes.any),
  onEnumSelect: React.PropTypes.func,
  onToggle: React.PropTypes.func,
  disabled: React.PropTypes.bool
}

export default EnumDropdown
