context = window
ptrCount = 0

@SessionTrackVU = React.createClass({


  render: () ->
    lights = []
    redSwitch = Math.round(this.props.lightCount * 0.66);
    lightClass = 'vu-red-off'

    if this.props.orientation == 'horizontal'

      for i in [0..this.props.lightCount-1]
        lightClass = if i >= redSwitch then 'vu-red-off' else 'vu-green-off'

        lightClasses = classNames('vulight', 'vu' + i, lightClass)

        lights.push(`<td key={i} width={this.props.lightWidth} height={this.props.lightHeight} className={lightClasses}></td>`)

        tableClasses = classNames('vu', 'horizontal')

      `<table className={tableClasses} data-light-count={this.props.lightCount}>
        <tbody>
          <tr>
            {lights}
          </tr>
        </tbody>
      </table>`
    else

      for i in [0..this.props.lightCount-1].reverse()
        lightClass = if (i >= redSwitch) then "vu-red-off" else "vu-green-off"

        lightClasses = classNames('vulight', 'vu' + i, lightClass)

        lights.push(`<tr key={i}><td width={this.props.lightWidth} height={this.props.lightHeight} className={lightClasses}></td></tr>`)

      tableClasses = classNames('vu', 'vertical')

      `<table className={tableClasses} data-light-count={this.props.lightCount}>
        <tbody>
          {lights}
        </tbody>
      </table>`

  getInitialState: () ->
    {registered: null, ptr: @props.ptr || "STV#{ptrCount++}"}

  registerVU: (mixer) ->

    mixerChanged = false
    if @state.registered? && mixer?

      # see if the mixer ID changed; if so, we need to unregister and re-register
      if @state.registered.mixer.id != mixer.id
        logger.debug("unregistering vu due to mixer change", @state.registered.mixer)
        context.JK.VuHelpers.unregisterVU(@state.registered.mixer, @state.registered.ptr)
        mixerChanged = true

    if !mixerChanged && (@state.registered? || !mixer?)
      return

    $root = $(this.getDOMNode())

    if mixerChanged
      logger.debug("re-registering VU #{context.JK.groupIdDisplay(mixer)}", mixer)
    #else
    #  logger.debug("registered VU #{context.JK.groupIdDisplay(mixer)}", mixer)

    context.JK.VuHelpers.registerVU(@props.side, mixer, @state.ptr, @props.orientation == 'horizontal', @props.lightCount, $root.find('td'))

    @setState(registered: {mixer: mixer, ptr: @state.ptr})


  componentWillReceiveProps: (nextProps) ->
    @registerVU(nextProps.mixers?.vuMixer)

  componentDidMount: () ->
    @registerVU(@props.mixers?.vuMixer)

  componentWillUnmount: () ->
    if @state.registered?
      #logger.debug("unregistered VU #{context.JK.groupIdDisplay(@state.registered.mixer)}")
      context.JK.VuHelpers.unregisterVU(@state.registered.mixer, @state.registered.ptr)

})