module Accounting
  class StatementsPage < UniversalPage
    include PageHelpers::ReactHelpers
    page_url "/accounting/statementshistory"

    buttons(:request_report, class: "btn-primary")
    buttons(:view_button, text: "View")
    table(:statements_table, class: %w[table table-striped])
    ul(:pagination, class: "pagination")
    div(:loading_bar, class: "progress")

    def wait_for_loading_bar_to_disappear
      loading_bar_element.element.wait_while(timeout: 60, &:present?)
    end

    def collect_all_revenues
      revenue = statements_table_element.trs.collect { |tr| tr[1].text }
      revenue.shift
      revenue
    end

    def rearrange_revenue_to_hash
      collect_all_revenues
      hashes = collect_all_revenues.each_with_object({})
                                   .with_index(1) { |(value, hash), i| hash["Revenue#{i}"] = value }
      hashes.delete_if { |_, value| value == "$0,00" }
      hashes
    end

    def click_on_last_period_with_revenue
      values = rearrange_revenue_to_hash.values
      statements_table_element[values.first]
    end

    def click_on_button_with_positive_revenue
      click_on_last_period_with_revenue.button(class: %w[btn btn-primary]).click
    end

    def click_on_link_with_positive_revenue
      click_on_last_period_with_revenue.button(class: %w[btn btn-link]).click
    end

    def first_statement_period
      wait_until { request_report_elements.any? }
      url = request_report_elements.last.attribute_value("href")
      url.scan(/\d{3}/)[1]
    end
  end
end
