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

context.JK.AccountPaymentHistoryScreen = class AccountPaymentHistoryScreen
  LIMIT = 20
  
  constructor: (@app) ->
    @logger = context.JK.logger
    @rest = context.JK.Rest()
    @screen = null
    @scroller = null
    @genre = null
    @artist = null
    @instrument = null
    @availability = null
    @nextPager = null
    @noMoreSales = null
    @currentPage = 0
    @next = null
    @tbody = null
    @rowTemplate = null

  beforeShow:(data) =>


  afterShow:(data) =>
    @refresh()

  events:() =>
    @backBtn.on('click', @onBack)

  onBack:() =>
    window.location = '/client#/account'
    return false

  clearResults:() =>
    @currentPage = 0
    @tbody.empty()
    @noMoreSales.hide()
    @next = null

  refresh:() =>
    @currentQuery = this.buildQuery()
    @rest.getSalesHistory(@currentQuery)
      .done(@salesHistoryDone)
      .fail(@salesHistoryFail)


  renderPayments:(response) =>
    if response.entries? && response.entries.length > 0
      for paymentHistory in response.entries
        if paymentHistory.sale?
          # this is a sale
          sale = paymentHistory.sale
          amt = sale.recurly_total_in_cents
          status = 'paid'
          displayAmount = ' $' + (amt/100).toFixed(2)
          date = context.JK.formatDate(sale.created_at, true)
          items = []
          for line_item in sale.line_items
            items.push(line_item.product_info?.name)
          description = items.join(', ')
        else
          # this is a recurly webhook
          transaction = paymentHistory.transaction
          amt = transaction.amount_in_cents
          status = transaction.transaction_type
          displayAmount = '($' + (amt/100).toFixed(2) + ')'
          date = context.JK.formatDate(transaction.transaction_at, true)
          description = transaction.admin_description

        payment = {
          date: date
          amount: displayAmount
          status: status
          payment_method: 'Credit Card'
          description: description
        }

        tr = $(context._.template(@rowTemplate, payment, { variable: 'data' }));
        @tbody.append(tr);
    else
      tr = "<tr><td class='center' colspan='5'>No payments found</td></tr>"
      @tbody.append(tr);

  salesHistoryDone:(response) =>

    # Turn in to HTML rows and append:
    #@tbody.html("")
    @next = response.next
    @renderPayments(response)
    if response.next == null
      # if we less results than asked for, end searching
      @scroller.infinitescroll 'pause'
      @logger.debug("end of history")
      if @currentPage > 0
        @noMoreSales.show()
        # there are bugs with infinitescroll not removing the 'loading'.
        # it's most noticeable at the end of the list, so whack all such entries
        $('.infinite-scroll-loader').remove()
    else
      @currentPage++
      this.buildQuery()
      this.registerInfiniteScroll()


  salesHistoryFail:(jqXHR)=>
    @noMoreSales.show()
    @app.notifyServerError jqXHR, 'Payment History Unavailable'

  defaultQuery:() =>
    query =
      per_page: LIMIT
      page: @currentPage+1
    if @next
      query.since = @next
    query

  buildQuery:() =>
    @currentQuery = this.defaultQuery()


  registerInfiniteScroll:() =>
    that = this
    @scroller.infinitescroll {
      behavior: 'local'
      navSelector: '#account-payment-history .btn-next-pager'
      nextSelector: '#account-payment-history .btn-next-pager'
      binder: @scroller
      dataType: 'json'
      appendCallback: false
      prefill: false
      bufferPx: 100
      loading:
        msg: $('<div class="infinite-scroll-loader">Loading ...</div>')
        img: '/assets/shared/spinner.gif'
      path: (page) =>
        '/api/payment_histories?' + $.param(that.buildQuery())

    }, (json, opts) =>
      this.salesHistoryDone(json)
    @scroller.infinitescroll 'resume'

  initialize:() =>
    screenBindings =
      'beforeShow': this.beforeShow
      'afterShow': this.afterShow
    @app.bindScreen 'account/paymentHistory', screenBindings
    @screen = $('#account-payment-history')
    @scroller = @screen.find('.content-body-scroller')
    @nextPager = @screen.find('a.btn-next-pager')
    @noMoreSales = @screen.find('.end-of-payments-list')
    @tbody = @screen.find("table.payment-table tbody")
    @rowTemplate = $('#template-payment-history-row').html()
    @backBtn = @screen.find('.back')

    if @screen.length == 0
      throw new Error('@screen must be specified')
    if @scroller.length == 0
      throw new Error('@scroller must be specified')
    if @tbody.length == 0
      throw new Error('@tbody must be specified')
    if @noMoreSales.length == 0
      throw new Error('@noMoreSales must be specified')

    this.events()
    

