$ = jQuery
context = window
context.JK ||= {};


context.JK.JamTrackPreview = {}
context.JK.JamTrackPreview = class JamTrackPreview
  constructor: (app, $root, jamTrack, jamTrackTrack, options) ->
    @EVENTS = context.JK.EVENTS
    @rest = context.JK.Rest()
    @logger = context.JK.logger
    @options = options || {master_shows_duration: false, color:'gray', add_line_break: false, preload_master:false}
    @app = app
    @jamTrack = jamTrack
    @jamTrackTrack = jamTrackTrack
    @root = $root
    @playButton = null
    @stopButton = null
    @instrumentIcon = null
    @instrumentName = null
    @part = null
    @loaded = false
    @loading = null
    @loadingText = null

    template = $('#template-jam-track-preview')
    throw "no jam track  preview template" if not template.exists()

    @root.html(context._.template(template.html(), @options, {variable:'data'}))
    @playButton = @root.find('.play-button')
    @stopButton = @root.find('.stop-button')
    @instrumentIcon = @root.find('.instrument-icon')
    @instrumentPart = @root.find('.instrument-part')
    @instrumentName = @root.find('.instrument-name')
    @part = @root.find('.part')
    @loading = @root.find('.loading')
    @loadingText = @root.find('.loading-text')
    @loadingTextText = @root.find('.loading-text-text')

    @playButton.on('click', @play)
    @stopButton.on('click', @stop)

    @root.attr('data-track-type', @jamTrackTrack.track_type).attr('data-id', @jamTrackTrack.id)
    instrumentId = null
    instrumentDescription = '?'
    if @jamTrackTrack.track_type == 'Track'
      @loadingTextText.text('20 second preview loading')
      if @jamTrackTrack.instrument
        instrumentId = @jamTrackTrack.instrument.id
        instrumentDescription = @jamTrackTrack.instrument.description
    else
      @loadingTextText.text('preview loading')
      instrumentId = 'other'
      instrumentDescription= 'Master Mix'

    instrument_src = context.JK.getInstrumentIcon24(instrumentId)

    @instrumentIcon.attr('data-instrument-id', instrumentId).attr('src', instrument_src)
    @instrumentName.text(instrumentDescription)
    #context.JK.bindInstrumentHover(@root)

    part = ''

    if @jamTrackTrack.track_type == 'Track'
      part = "#{@jamTrackTrack.part}" if @jamTrackTrack.part? && @jamTrackTrack.part != instrumentDescription
      @part.text("(#{part})") if part != ''
    else
      if @options.master_adds_line_break
        part = '"' + @jamTrack.name + '"' + ' by ' + @jamTrack.original_artist

        @part.text("#{part}") if part != ''
        @part.addClass('adds-line-break')
      else

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

        @part.text("(#{part})") if part != ''


    @instrumentPart.text(@instrumentName.text() + ' ' + @part.text())

    if @jamTrackTrack.preview_mp3_url?

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

      @no_audio = false
    else
      @no_audio = true

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

  onDestroyed: () =>
    @sound.unload()

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


  onHowlerEnd: () =>
    @logger.debug("on end $(this)", $(this))
    @stopButton.addClass('hidden')
    @playButton.removeClass('hidden')
    @removeNowPlaying()

  onHowlerLoad: () =>
    @loaded = true
    @loading.fadeOut(2000);
    @loadingText.fadeOut(2000); #addClass('hidden')

  play: (e) =>
    if e?
      e.stopPropagation()

    $(this).triggerHandler(@EVENTS.PREVIEW_PLAYED)

    if @no_audio
      context.JK.prodBubble(@playButton, 'There is no preview available for this track.', {}, {duration:2000})
    else
      unless @sound?
        @root.on('remove', @onDestroyed);

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

      unless @loaded
        @loading.removeClass('hidden')
        @loadingText.removeClass('hidden')


      @logger.debug("play issued for jam track preview")
      @sound.play()
      context.JamTrackPreviewActions.startedPlaying(this)
      @playButton.addClass('hidden')
      @stopButton.removeClass('hidden')

    return false

  issueStop: () =>
    @logger.debug("pause issued for jam track preview")
    @sound.pause() # stop does not actually stop in windows client
    @stopButton.addClass('hidden')
    @playButton.removeClass('hidden')

  stop: (e) =>
    if e?
      e.stopPropagation()

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


    return false



