context = window
ReactCSSTransitionGroup = React.addons.CSSTransitionGroup

@JamTrackPreview = React.createClass({

  mixins: [Reflux.listenTo(@AppStore, "onAppInit")]
  EVENTS: context.JK.EVENTS
  logger: context.JK.logger
  propTypes: { options: React.PropTypes.object }

  getDefaultProps: () ->
    { options: {master_shows_duration: false, color: 'gray', add_line_break: false, preload_master: false}}

  getInitialState: () ->
    { loaded: false, loading: false, playing: false, no_audio: false }

  render: () ->
    playButtonClasses  = { "play-button": true, disabled: @state.no_audio}
    playButtonClasses[@props.options.color] = @props.options.color?
    playButtonClasses = classNames(playButtonClasses)

    stopButtonClasses  = { "stop-button": true, disabled: @state.no_audio }
    stopButtonClasses[@props.options.color] = @props.options.color?
    stopButtonClasses = classNames(stopButtonClasses)

    partClasses = {part: true}
    partClasses['adds-line-break'] = true if  @props.options.master_adds_line_break
    partClasses = classNames(partClasses)

    if @state.playing
      activeButton = `<a className={stopButtonClasses} onClick={this.stop} />`
    else
      activeButton = `<a className={playButtonClasses} onClick={this.play} />`

    loaders = []
    if @props.jamTrackTrack.track_type == 'Track'
      loading_text = '20 second preview loading'
    else
      loading_text = 'preview loading'


    if @state.loading
      loaders.push `<div key="text" className="loading-text">{loading_text}
        <div className="loading spinner-small"></div>
      </div>`


    `<div className="jam-track-preview" data-track-type={this.props.jamTrackTrack.track_type} data-id={this.props.jamTrackTrack.id}>
      <div className="actions">
        {activeButton}
      </div>
      <img className="instrument-icon" data-hoveraction="instrument" data-instrument-id={this.state.instrumentId} src={this.state.instrumentSrc} width="24" height="24" />
      <div className="instrument-name">{this.state.instrumentDescription}</div>
      <div className="part">{this.state.part}</div>
      <ReactCSSTransitionGroup transitionName="session-track-list" transitionAppear={true}>
        {loaders}
      </ReactCSSTransitionGroup>
    </div>`


  componentWillMount: () ->
    instrumentId = null
    instrumentDescription = '?'
    if @props.jamTrackTrack.track_type == 'Track'
      if @props.jamTrackTrack.instrument
        instrumentId = @props.jamTrackTrack.instrument.id
        instrumentDescription = @props.jamTrackTrack.instrument.description
    else
      instrumentId = 'other'
      instrumentDescription= 'Master Mix'

    instrumentSrc = context.JK.getInstrumentIcon24(instrumentId)

    part = ''

    if @props.jamTrackTrack.track_type == 'Track'
      part = "(#{@props.jamTrackTrack.part})" if @props.jamTrackTrack.part? && @props.jamTrackTrack.part != instrumentDescription

    else
      if @props.options.master_adds_line_break
        part = '"' + @props.jamTrack.name + '"' + ' by ' + @props.jamTrack.original_artist
      else
        if @props.options.master_shows_duration
          duration = 'entire song'
          if @props.jamTrack.duration
            duration = "#{context.JK.prettyPrintSeconds(@props.jamTrack.duration)}"
          part = duration
        else
          part = @props.jamTrack.name + ' by ' + @props.jamTrack.original_artist

          part = "(#{part})" unless part?
    part = '' unless part?

    urls = null
    no_audio = null

    if @props.jamTrackTrack.preview_mp3_url?

      urls = [@props.jamTrackTrack.preview_mp3_url]
      if @props.jamTrackTrack.preview_ogg_url?
        urls.push(@props.jamTrackTrack.preview_ogg_url)
      urls = urls

      no_audio = false
    else
      no_audio = true


    @setState({
      instrumentId: instrumentId,
      instrumentDescription: instrumentDescription,
      instrumentSrc: instrumentSrc,
      part: part
      urls: urls,
      no_audio: no_audio})

  componentDidMount: () ->
    $root = $(@getDOMNode());

    if @props.options.preload_master && @props.jamTrackTrack.track_type == 'Master' && !@state.no_audio
      @sound = new Howl({
        src: @state.urls,
        autoplay: false,
        loop: false,
        volume: 1.0,
        preload: true,
        onload: @onHowlerLoad
        onend: @onHowlerEnd})

  componentWillUnmount: () ->
    @sound.unload() if @sound?

  removeNowPlaying: () ->
    context.JamTrackPreviewActions.stoppedPlaying(this)

  onHowlerEnd: () ->
    @logger.debug("on end")
    @removeNowPlaying()
    @setState(playing: false)

  onHowlerLoad: () ->
    @setState(loaded: true, loading: false)

  play: (e) ->
    if e?
      e.stopPropagation()
      e.preventDefault()

    $root = $(@getDOMNode())
    $root.triggerHandler(@EVENTS.PREVIEW_PLAYED)

    $playButton = $root.find('.play-button')
    if @state.no_audio
      context.JK.prodBubble($playButton, 'There is no preview available for this track.', {}, {duration:2000})
    else
      unless @sound?

        @sound = new Howl({
          src: @state.urls,
          autoplay: false,
          loop: false,
          volume: 1.0,
          preload: true,
          onload: @onHowlerLoad
          onend: @onHowlerEnd})


      @logger.debug("play issued for jam track preview")
      @sound.play()
      context.JamTrackPreviewActions.startedPlaying(this)
      @setState({playing: true, loading: !@state.loaded})

  issueStop: () ->
    @logger.debug("pause issued for jam track preview")
    @sound.pause() if @sound? # stop does not actually stop in windows client
    @setState({playing: false})

  stop: (e) ->
    if e?
      e.stopPropagation()
      e.preventDefault()

    if @state.no_audio
      context.JK.helpBubble(@playButton, 'There is no preview available for this track.', {}, {duration:2000})
    else
      @issueStop()
      @removeNowPlaying()

    return false

})
