import React, { Component } from 'react'
import ReactSlider from 'rc-slider'
import SliderBarEntry from './SliderBarEntry'
import 'rc-slider/dist/rc-slider.css'
import './SliderBar.scss'

class SliderBar extends Component {

  constructor (props) {
    super(props)
    this.getTipStr = this.getTipStr.bind(this)
    this.onSliderChange = this.onSliderChange.bind(this)
    this.state = {
      curIdx: undefined
    }
  }

  getTipStr (idx) {
    if (idx < 0) {
      return ''
    }
    return this.props.values[idx].name
  }

  onSliderChange (idx) {
    if (idx < 0 || this.props.disabled) {
      return
    }
    this.setState({ curIdx: idx })
    this.props.onChange(this.props.values[idx].id)
  }

  getElement () {
    let values = this.props.values
    const minIdx = 0
    const maxIdx = values.length - 1
    let marks = {}
    values.forEach((value, idx) => {
      if (idx === minIdx) {
        marks[idx] = value.shortName
      } else if (idx === maxIdx) {
        marks[idx] = value.shortName
      } else {
        marks[idx] = ''
      }
    })

    return (
      <ReactSlider
        min={minIdx}
        max={maxIdx}
        marks={marks}
        tipFormatter={this.getTipStr}
        value={this.props.value}
        onChange={this.onSliderChange}
        disabled={this.props.disabled}
      />
    )
  }

  render () {
    let element = this.getElement()
    return (
      <div className='slider-bar-container'>
        {element}
      </div>
    )
  }
}

SliderBar.propTypes = {
  values: React.PropTypes.arrayOf(React.PropTypes.instanceOf(SliderBarEntry)),
  onChange: React.PropTypes.func,
  disabled: React.PropTypes.bool,
  value: React.PropTypes.number
}

SliderBar.defaultProps = {
  defaultValue: 0
}

export default SliderBar
