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

context.JK.AccountJamTracks = class AccountJamTracks
  constructor: (@app) ->
    @rest = context.JK.Rest()
    @client = context.jamClient
    @logger = context.JK.logger
    @screen = null
    @userId = context.JK.currentUserId;
    @sessionUtils = context.JK.SessionUtils

  initialize:() =>
    screenBindings =
      'beforeShow': @beforeShow
      'afterShow': @afterShow
    @app.bindScreen('account/jamtracks', screenBindings)
    @screen = $('#account-jamtracks')    
    
  beforeShow:() =>
    rest.getPurchasedJamTracks({limit: 40})
      .done(@populateJamTracks)
      .fail(@app.ajaxError);

  afterShow:() =>
    
  populateJamTracks:(data) =>
    if (data.jamtracks? && data.jamtracks.length > 0) 
      @screen.find(".no-jamtracks-found").addClass("hidden")
      @appendJamTracks(data)
      @screen.find('.jamtrack-solo-session').on 'click', @soloSession
      @screen.find('.jamtrack-group-session').on 'click', @groupSession
    else
      @screen.find(".no-jamtracks-found").removeClass("hidden")
    
  appendJamTracks:(data) =>

    $tbody = $('#account-my-jamtracks table tbody')
    $tbody.empty()

    for jamTrack in data.jamtracks
      $template = $(context._.template($('#template-account-jamtrack').html(), {jamtrack:jamTrack}, { variable: 'data' }))
      $template.data('jamTrack', jamTrack)
      $tbody.append($template)


  soloSession:(e) =>
    #context.location="client#/createSession"
    jamRow = $(e.target).parents("tr")
    @createSession(jamRow.data(), true, jamRow.data('jamTrack'))
    return false;
    
  groupSession:(e) =>
    #context.location="client#/createSession"
    jamRow = $(e.target).parents("tr")
    @createSession(jamRow.data(), false, jamRow.data('jamTrack'))
    return false;
    
  createSession:(sessionData, solo, jamTrack) =>
    tracks = context.JK.TrackHelpers.getUserTracks(context.jamClient)

    if (context.JK.guardAgainstBrowser(@app)) 
      data = {}
      data.client_id = @app.clientId
      #data.description = $('#description').val()
      data.description = "Jam Track Session"
      data.as_musician = true
      data.legal_terms = true
      data.intellectual_property = true
      data.approval_required = false
      data.musician_access = !solo
      data.fan_access = false
      data.fan_chat = false
      data.genre = $.map(sessionData.jamTrack.genres, (genre) ->  genre.id)
      data.genres = $.map(sessionData.jamTrack.genres, (genre)->  genre.id)
      # data.genres = context.JK.GenreSelectorHelper.getSelectedGenres('#create-session-genre')
      # data.musician_access = if $('#musician-access option:selected').val() == 'true' then true else false
      # data.approval_required = if $('input[name=\'musician-access-option\']:checked').val() == 'true' then true else false
      # data.fan_access = if $('#fan-access option:selected').val() == 'true' then true else false
      # data.fan_chat = if $('input[name=\'fan-chat-option\']:checked').val() == 'true' then true else false
      # if $('#band-list option:selected').val() != ''
      #   data.band = $('#band-list option:selected').val()
      data.audio_latency = context.jamClient.FTUEGetExpectedLatency().latency
      data.tracks = tracks

      rest.legacyCreateSession(data).done((response) =>
        newSessionId = response.id
        @sessionUtils.setAutoOpenJamTrack(jamTrack) # so that the session screen will pick this up
        context.location = '/client#/session/' + newSessionId        
        # Re-loading the session settings will cause the form to reset with the right stuff in it.
        # This is an extra xhr call, but it keeps things to a single codepath
        #loadSessionSettings()
        context.JK.GA.trackSessionCount data.musician_access, data.fan_access, 0
        context.JK.GA.trackSessionMusicians context.JK.GA.SessionCreationTypes.create      
      ).fail (jqXHR) =>
        handled = false
        if jqXHR.status = 422
          response = JSON.parse(jqXHR.responseText)
          if response['errors'] and response['errors']['tracks'] and response['errors']['tracks'][0] == 'Please select at least one track'
            @app.notifyAlert 'No Inputs Configured', $('<span>You will need to reconfigure your audio device.</span>')
            handled = true
        if !handled
          @app.notifyServerError jqXHR, 'Unable to Create Session'
        