import React, {PropTypes, Component} from 'react'
import _ from 'lodash'
import uuid from 'node-uuid'

const style = {
  position: 'absolute',
  width: 'calc(100% - 32px)',
  bottom: '8px',
  left: '16px',
  height: '30px',
}

const removeMeasurement = (label = '') => {
  const [measurement] = label.match(/^(.*)[.]/g) || ['']
  return label.replace(measurement, '')
}

const persistentLegendItemClassname = (visibilities, i) => {
  if (visibilities.length) {
    return `persistent-legend--item${visibilities[i] ? '' : ' disabled'}`
  }

  // all series are visible to match expected initial state
  return 'persistent-legend--item'
}

class PersistentLegend extends Component {
  constructor(props) {
    super(props)

    this.state = {
      visibilities: [],
    }
  }

  handleClick = i => e => {
    const visibilities = this.props.dygraph.visibility()
    const selected =
      this.state.selected || _.fill(Array(visibilities.length), false)

    if (e.shiftKey || e.metaKey) {
      visibilities[i] = !visibilities[i]
      this.props.dygraph.setVisibility(visibilities)
      this.setState({visibilities})
      return
    }
  }

  render() {
    const {dygraph} = this.props
    const {visibilities} = this.state

    const labels = dygraph ? _.drop(dygraph.getLabels()) : []
    const colors = dygraph
      ? _.map(labels, l => {
          return dygraph.attributes_.series_[l].options.color
        })
      : []

    /* Add style={{color: seriesColor}} to <div> & <span> below */
    return (
      <div className="persistent-legend" style={style}>
        {_.map(labels, (v, i) =>
          <div
            className={persistentLegendItemClassname(visibilities, i)}
            key={uuid.v4()}
            onClick={this.handleClick(i)}
          >
            <div
              className="persistent-legend--dot"
              style={{backgroundColor: colors[i]}}
            />
            <span style={{color: colors[i]}}>
              {removeMeasurement(v)}
            </span>
          </div>
        )}
      </div>
    )
  }
}

const {shape} = PropTypes

PersistentLegend.propTypes = {sharedLegend: shape({}), dygraph: shape({})}

export default PersistentLegend

@@ -857,100 +857,8 @@
 ty()
-%0A    const selected =%0A      this.state.selected %7C%7C _.fill(Array(visibilities.length), false)
 %0A%0A  
@@ -1034,24 +1034,282 @@
 return%0A    %7D
+%0A%0A    const newVisibilities = visibilities%5Bi%5D%0A      ? _.map(visibilities, v =%3E !v)%0A      : _.map(visibilities, v =%3E false)%0A    newVisibilities%5Bi%5D = true%0A%0A    this.props.dygraph.setVisibility(newVisibilities)%0A    this.setState(%7Bvisibilities: newVisibilities%7D)
 %0A  %7D%0A%0A  rend
@@ -1594,75 +1594,8 @@
 %5B%5D%0A%0A
-    /* Add style=%7B%7Bcolor: seriesColor%7D%7D to %3Cdiv%3E & %3Cspan%3E below */%0A
     

Add regular click behavior to persistent legend