

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

class AffiliateLinks
  constructor: (@app, @partner_id) ->
    @logger = context.JK.logger
    @rest = new context.JK.Rest();

  initialize: () =>
    @page = $('body')
    @sections = ['jamtrack_songs', 'jamtrack_bands', 'jamtrack_general', 'jamkazam', 'sessions', 'recordings']
    @jamtrack_songs = @page.find('table.jamtrack_songs tbody')
    @jamtrack_bands = @page.find('table.jamtrack_bands tbody')
    @jamtrack_general = @page.find('table.jamtrack_general tbody')
    @jamkazam = @page.find('table.jamkazam tbody')
    @sessions= @page.find('table.sessions tbody')
    @recordings = @page.find('table.recordings tbody')

    @iterate()

  onGetLinks: (links) =>

    $table = @page.find('table.' + @section + ' tbody')
    template = $('#template-affiliate-link-row').html();
    context._.each(links, (item) =>
      $link = $(context._.template(template, item, {variable: 'data'}));
      $link.find('td.copy-link a').click(@copyLink)
      $table.append($link)
    )

    if @sections.length > 0
      @iterate()


  copyLink: () ->
    $element = $(this)
    $url = $element.closest('tr').find('td.url input')
    $url.select()

    return false;


  iterate: () =>
    @section = @sections.shift()

    @rest.getLinks(@section, @partner_id)
      .done(@onGetLinks)



context.JK.AffiliateLinks = AffiliateLinks

