require "bigdecimal"
require "bigdecimal/util" # for #to_d

class BreakdownPage < BasePage
  include MathHelper

  page_url "#{ENVied.WORKSTATION_URL}/accounting"

  div(:statement_table, id: "statement")
  # the following elements are for the upper most accounting statement which is comprised of dl and dd tags
  element(:opening_balance, :element, id: "openingBalance")
  element(:revenue, :element, id: "netReceipt")
  element(:publishing, :element, id: "totalPublishing")
  element(:adjustments, :element, id: "totalAdjustments")
  element(:payment, :element, id: "totalPayment")
  elements(:check, :element, class: "check-amount")
  element(:ringtones, :element, id: "ringtonePublishing")
  element(:full_tracks, :element, id: "fullTracksPublishing")
  element(:outstanding_balance, :element, id: "outstandingBalance")
  element(:encoding_fees, :element, id: "encodingFees")
  element(:advance_paid, :element, id: "advancePaid")

  # TODO: fix cop violations
  def expected_outstanding_balance # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
    # while still preserving negative amount
    c = ->(string) { string.gsub(/[^\d-]/, "").to_d / 100 }
    s = ->(decimal) { format("%.2f", decimal) } # Format to 2 decimal places

    running_total = 0
    running_total += c.call opening_balance_element.when_present.text
    running_total += c.call advance_paid if advance_paid? # Adding because this is a negative value in the UI
    running_total += c.call revenue if revenue?
    running_total += c.call encoding_fees if encoding_fees?
    running_total += c.call full_tracks if full_tracks?
    running_total += c.call ringtones if ringtones?
    running_total += c.call adjustments if adjustments?
    running_total += c.call payment if payment?
    puts "calculated total: #{s.call running_total}"

    outstanding_bal = c.call outstanding_balance
    puts "outstanding balance on page: #{s.call outstanding_bal}"
    puts "difference (should be within 1.00!): #{s.call(outstanding_bal - running_total)}"
    expect(outstanding_bal).to be_within(1.00).of(running_total)
    running_total
  end
end
