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

context.JK.JamTrackLanding = class JamTrackLanding
  constructor: (@app) ->
    @rest = context.JK.Rest()
    @client = context.jamClient
    @logger = context.JK.logger
    @screen = null
    @noFreeJamTrack = null
    @freeJamTrack = null
    @bandList = null
    @noBandsFound = null

  initialize:() =>
    screenBindings =
      'beforeShow': @beforeShow
      'afterShow': @afterShow
    @app.bindScreen('jamtrackLanding', screenBindings)
    @screen = $('#jamtrackLanding')
    @noFreeJamTrack = @screen.find('.no-free-jamtrack')
    @freeJamTrack = @screen.find('.free-jamtrack')
    @bandList = @screen.find('#band_list')
    @noBandsFound = @screen.find('#no_bands_found')

  beforeShow:() =>

    @noFreeJamTrack.addClass('hidden')
    @freeJamTrack.addClass('hidden')

  afterShow:() =>

    if context.JK.currentUserId
      @app.user().done(@onUser)
    else
      @onUser({free_jamtrack: gon.global.one_free_jamtrack_per_user})

  onUser:(user) =>
    if user.free_jamtrack
      @freeJamTrack.removeClass('hidden')
    else
      @noFreeJamTrack.removeClass('hidden')

    # Get artist names and build links
    @rest.getJamTrackArtists({group_artist: true, per_page:100})
    .done(this.buildArtistLinks)
    .fail(this.handleFailure)

    # Bind links to action that will open the jam_tracks list view filtered to given artist_name:
    # artist_name
    this.bindArtistLinks()

  buildArtistLinks:(response) =>
    # Get artist names and build links
    @logger.debug("buildArtest links response", response)

    artists = response.artists
    $("#band_list>li:not('#no_bands_found')").remove()
    if artists.length==0
      @noBandsFound.removeClass("hidden")
    else
      @noBandsFound.addClass("hidden")

    # client#/jamtrack
    for artist in artists
      artistLink = "<a href='client?artist=#{encodeURIComponent(artist.original_artist)}#/jamtrackBrowse' class='artist-link' artist='#{artist.original_artist}'>#{artist.original_artist} (#{artist.song_count})</a>"
      @bandList.append("<li>#{artistLink}</li>")

  # We don't want to do a full page load if this is clicked on here:
  bindArtistLinks:() =>
    that=this
    @bandList.on "click", "a.artist-link", (event)->
      context.location="client#/jamtrackBrowse"
      if window.history.replaceState # ie9 proofing
        window.history.replaceState({}, "", this.href)
      event.preventDefault()
      
  handleFailure:(error) =>
