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

context.JK.JamtrackPaymentHistoryDialog = class JamtrackPaymentHistoryDialog
  constructor: (@app) ->
    @rest = context.JK.Rest()
    @client = context.jamClient
    @logger = context.JK.logger
    @screen = null
    @dialogId = 'jamtrack-payment-history-dialog';
    @dialog = null;    
    
  initialize:() =>
    dialogBindings = {
      'beforeShow' : @beforeShow,
      'afterShow' : @afterShow
    }

    @dialog = $('[layout-id="' + @dialogId + '"]');
    @app.bindDialog(@dialogId, dialogBindings);
    @tbody = @dialog.find("table.payment-table tbody")
    @rowTemplate = $('#template-payment-history-row').html()
    
  beforeShow:() =>
    # Get payment history from jamrest
    payments = [
      {date: new Date(2013, 4, 5), amount: 372.33},
      {date: new Date(2014, 5, 5), amount: 338.44}
    ]
    
    @rest.getPaymentHistory()
      .done(@showPaymentHistory)
      .fail(@app.ajaxError)

  showPaymentHistory:(data) =>
    # Turn in to HTML rows and append:
    @tbody.html("")
    if data.payments? && data.payments.length > 0
      for p in data.payments
        amt = p.amount
        amt = 0 if !amt?
        payment = {
          date: context.JK.formatDateYYYYMMDD(p.created_at)
          amount: (amt * 100).toFixed(2)
          status: p.status
          payment_method: p.payment_method.replace("_", " ")
          reference: p.reference
        }
        tr = $(context._.template(@rowTemplate, payment, { variable: 'data' }));
        @tbody.append(tr);
    else
      tr = "<tr><td colspan='5'>No payments found</td></tr>"
      @tbody.append(tr);

  afterShow:() =>

  showDialog:() =>
    @app.layout.showDialog(@dialogId)

  