'use strict'

import React, { PropTypes } from 'react'

const draw = (width, height, canvasCtx, volume) => {
  canvasCtx.clearRect(0, 0, width, height)
  for (let i = 0; i < 5; i++) {
    canvasCtx.fillStyle = (i * 256 / 5 < volume) ? 'green' : 'grey'
    const x = width * i / 5
    const y = height * 0.6 - height * i * 0.15
    canvasCtx.fillRect(x, y, width / 6, height - y)
  }
}

const VolumeMeter = React.createClass({
  getVolume () {
    this.analyser.getByteFrequencyData(this.array)
    const length = this.array.length
    let total = 0

    for (let i = 0; i < length; i++) {
      total += this.array[i]
    }
    return total / length
  },

  start () {
    const { width, height } = this.props
    const canvasCtx = this.refs.canvas.getContext('2d')

    const drawLoop = () => {
      draw(width, height, canvasCtx, this.getVolume())
      this.rafId = window.requestAnimationFrame(drawLoop)
    }

    drawLoop()
  },

  componentDidMount () {
    const { width, height } = this.props
    const canvasCtx = this.refs.canvas.getContext('2d')

    draw(width, height, canvasCtx, 0)
  },

  componentWillUpdate (nextProps) {
    if (!this.props.src && nextProps.src) {
      const { audioContext, src } = this.props
      this.analyser = audioContext.createAnalyser()
      src.connect(this.analyser)
      this.array = new Uint8Array(this.analyser.frequencyBinCount)
    }
  },

  render () {
    const { width, height } = this.props
    const st = {
      width: width,
      height: height
    }

    return (
      <canvas
        ref='canvas'
        style={st}
      />
    )
  },

  propTypes: {
    audioContext: PropTypes.object.isRequired,
    src: PropTypes.object,
    width: PropTypes.number.isRequired,
    height: PropTypes.number.isRequired
  }
})

export default VolumeMeter

@@ -210,17 +210,17 @@
  (i * 25
-6
+5
  / 5 %3C v
@@ -789,16 +789,54 @@
 () =%3E %7B%0A
+      if (this.analyser.ended) return%0A
       dr
@@ -960,32 +960,94 @@
 rawLoop()%0A  %7D,%0A%0A
+  stop () %7B%0A    window.cancelAnimationFrame(this.rafId)%0A  %7D,%0A%0A
   componentDidMo
@@ -1488,16 +1488,208 @@
 %7D%0A  %7D,%0A%0A
+  componentDidUpdate (prevProps) %7B%0A    if (this.props.command && this.props.command !== 'none' && this.prevProps.command !== this.props.command) %7B%0A      this%5Bthis.props.command%5D()%0A    %7D%0A  %7D,%0A%0A
   render
@@ -1888,16 +1888,16 @@
 )%0A  %7D,%0A%0A
-
   propTy
@@ -1903,16 +1903,73 @@
 ypes: %7B%0A
+    command: PropTypes.oneOf(%5B'start', 'stop', 'none'%5D),%0A
     audi

add command prop