context = window

MixerActions = @MixerActions
ConfigureTracksActions = @ConfigureTracksActions

@SessionMyTrack = React.createClass({

  mixins: [Reflux.listenTo(@SessionStatsStore,"onStatsChanged")]

  onStatsChanged: (stats) ->
    @setState({stats: stats[@props.clientId]})

  getInitialState: () ->
    stats = window.SessionStatsStore.stats
    if stats?
      clientStats = stats[@props.clientId]
    else
      clientStats = null
    {stats: clientStats}

  handleMute: (e) ->
    e.preventDefault()

    unless this.props.mixers.mixer
      logger.debug("ignoring mute; no mixer")
      return

    muting = $(e.currentTarget).is('.enabled')

    # this button is annoying. the hover shows mute and it's good to use instead
    # MixerActions.mute([this.props.mixers.mixer, this.props.mixers.oppositeMixer], muting)

  render: () ->

    muteMixer = this.props.mixers.muteMixer
    vuMixer = this.props.mixers.vuMixer
    muteMixerId = muteMixer?.id

    classes = classNames({
      'track-icon-mute': true
      'enabled' : !muteMixer?.mute
      'muted' : muteMixer?.mute
    })

    trackClasses = classNames({
      'session-track' : true
      'my-track' : true
      'has-mixer' : this.props.hasMixer
      'no-mixer' : !this.props.hasMixer
    })

    unless @props.no_pan
      pan = if this.props.mixers.mixer? then this.props.mixers.mixer.pan else 0

      panStyle = {
        transform: "rotate(#{pan}deg)"
        WebkitTransform: "rotate(#{pan}deg)"
      }

      panJsx = `<div className="track-icon-pan" style={panStyle}/>`

    classification = @state.stats?.classification

    if !classification?
      classification = 'unknown'

    connectionStateClasses = { 'track-connection-state': true}
    connectionStateClasses[classification] = true

    if @props.associatedVst?
      @equalizerSet = true
      vst = `<div className="track-icon-equalizer" />`

    `<div className={trackClasses}>
      <div className="disabled-track-overlay" />
      <div className="session-track-contents">
        <div className="name">{this.props.trackName}</div>
        <div className="track-avatar"><img src={this.props.photoUrl}/></div>
        <div className="track-instrument"><img height="45" src={this.props.instrumentIcon} width="45" /></div>
        <div className="track-controls">
          <SessionTrackVU orientation="horizontal" lightCount={5} lightWidth={17} lightHeight={3} side="best" mixers={this.props.mixers} />
          <div className="track-buttons">
            <div className={classes} data-control="mute" data-mixer-id={muteMixerId} onClick={this.handleMute}/>
            {panJsx}
            {vst}
            <div className={classNames(connectionStateClasses)}/>
          </div>
          <br className="clearall"/>
        </div>
        <br className="clearall"/>
      </div>
    </div>`

  componentDidMount: () ->

    context.jamClient.SessionSetUserName(this.props.clientId, this.props.name)

    $root = $(this.getDOMNode())
    $mute = $root.find('.track-icon-mute')
    $pan  = $root.find('.track-icon-pan')
    $connectionState = $root.find('.track-connection-state')

    context.JK.interactReactBubble(
      $mute,
      'SessionTrackVolumeHover',
      () =>
        {mixers:this.props.mixers, trackType: 'SessionMyTrack', mode: @props.mode}
      ,
      {width:235, positions:['right', 'left'], offsetParent:$root.closest('.top-parent')})

    context.JK.interactReactBubble(
      $pan,
      'SessionTrackPanHover',
      () =>
        {mixers:this.props.mixers}
      ,
      {width:331, positions:['right', 'left'], offsetParent:$root.closest('.top-parent')})

    context.JK.interactReactBubble(
      $connectionState,
      'SessionStatsHover',
      () =>
        {myTrack: true, participant: {client_id: this.props.connStatsClientId, user: name: 'You', possessive: 'Your'}, }
    ,
      {width:385, positions:['right', 'left'], offsetParent:$root.closest('.screen'), extraClasses: 'self'})

    unless this.props.hasMixer
      $mute.on("mouseenter", false)
      $mute.on("mouseleave", false)
      $pan.on("mouseentere", false)
      $pan.on("mouseleave", false)
    unless this.props.hasMixer
      $mute.on("mouseenter", false)
      $mute.on("mouseleave", false)
      $pan.on("mouseentere", false)
      $pan.on("mouseleave", false)

    context.JK.helpBubble($root.find('.disabled-track-overlay'), 'missing-my-tracks', {}, {positions:['top'], offsetParent: $root.closest('.top-parent')})

    @initializeVstEffects()

  componentWillUpdate: (nextProps, nextState) ->
    $root = $(this.getDOMNode())
    $mute = $root.find('.track-icon-mute')
    $pan  = $root.find('.track-icon-pan')

    # disable hover effects if there is no mixer
    if nextProps.mixers.mixer?
      $mute.off("click", false)
      $pan.off("click", false)
      $mute.off("mouseenter", false)
      $mute.off("mouseleave", false)
      $pan.off("mouseenter", false)
      $pan.off("mouseleave", false)
    else
      $mute.on("click", false)
      $pan.on("click", false)
      $mute.on("mouseenter", false)
      $mute.on("mouseleave", false)
      $pan.on("mouseentere", false)
      $pan.on("mouseleave", false)

  componentDidUpdate:() ->
    @initializeVstEffects()

  initializeVstEffects: () ->
    $root = $(this.getDOMNode())
    $equalizer = $root.find('.track-icon-equalizer')
    if $equalizer.length > 0 && !$equalizer.data('initialized')
      logger.debug("initializing trackEffects", $equalizer)
      $equalizer.trackEffects({postShow: @prepVstEffects}).on(context.JK.EVENTS.VST_EFFECT_SELECTED, @vstOperation).data('initialized', true).click(() =>
        logger.debug("clicked!")
        $equalizer.btOn()
      )
  prepVstEffects: ($container) ->
    $container.find('.vst-name').text(@props.associatedVst?.name)

  vstOperation: (e, data) ->
    logger.debug("track effect selection: " + data.vstOperation)

    if !@props.associatedVst?
      logger.warn("no associated VST")
      return

    if data.vstOperation == 'open-vst'
      ConfigureTracksActions.showVstSettings(@props.associatedVst.track)
    else
      # configure tracks does some sort of init that is required for this to work

      originalTrack = @props.associatedVst.track + 1
      context.JK.app.layout.showDialog('configure-tracks')
      ConfigureTracksActions.showEditTrack(originalTrack)

})
