Then(/^I should be on the accounting breakdown page$/) do
  on(Workstation::AccountingBreakdownPage) do |page|
    expect(page.current_url).to include page.page_url_value
  end
end

When(/^I click 'Request Report' button for last period with positive revenue$/) do
  on(Accounting::StatementsPage) do |page|
    page.wait_until(90) { page.request_report_elements.count >= 1 }
    period = page.statements_table_element.trs.find do |p|
      p[1].text.delete("$").to_i > 0
    end
    period.buttons.find { |b| b.text == "REQUEST REPORT" }.click
  end
end

Then(/^I should see report form with all required elements$/) do
  on(Accounting::RequestReportPage) do |page|
    expect(page.on_label("xls").text).to eq("Download in .xls format")
    expect(page.on_label("txt").text).to eq("Download in .txt format")
    expect(page.on_label("en_US").text).to eq("Download in US format (Example: 10,000.50 USD)")
    expect(page.on_label("es_ES").text).to eq("Download in EU format (Example: 10.000,50 USD)")
    expect(page.on_label("custom").text).to eq("Custom Report")
    expect(page.on_label("physical").text).to eq("Physical Only Report")
    expect(page.on_label("full").text).to eq("Full Report")
    expected_page_header = "Request Report for #{page.url.scan(/\w+_\d+/).first.tr('_', ' ')}"
    expect(page.page_header).to eq(expected_page_header)
    expect(page.request_report_button?).to be true
    expect(page.cancel_link?).to be true
  end
end

When(/^I cancel the report request$/) do
  on(Accounting::RequestReportPage) do |page|
    expect(page.cancel_link?).to be true
    page.cancel_link
  end
end

Then(/^I should be redirected to the statements page$/) do
  on(Accounting::StatementsPage) do |page|
    expect(page.current_url.end_with?(page.page_url_value))
    page.wait_until { page.request_report_elements.count > 1 }
    expect(page.request_report_elements.first.exists?).to be true
  end
end

When(/^I attempt to generate (.*?) report$/) do |report_type|
  on(Accounting::RequestReportPage) do |page|
    @report_period = page.page_header.split(" ").last(2).join
    @selected_report_number_format ||= "US"
    @selected_report_file_type ||= "xls"
    @selected_report_type = report_type
    page.on_label(report_type).click
    if report_type == "custom"
      page.wait_for_transaction_section
      @expected_transaction_type = page.select_transactions_types
    end
    page.request_report_button
  end
end

Then(/^I should see download duplicate report link$/) do
  on(Accounting::RequestReportPage) do |page|
    page.error_dialog_header_element.wait_until(&:present?)
    expect(page.error_dialog_header).to start_with("Duplicate Report")
    expect(page.download_link_element.text).to eq("here")
  end
end

When(/^I try to download file$/) do
  on(Accounting::RequestReportPage) do |_page|
    @accounting_user ||= @users.accounting_user
    headers = Support::Services::OwsAccounting.generate_headers(@accounting_user)
    number_format = Support::Services::OwsAccounting.number_format_matcher(@selected_report_number_format)
    report_format = Support::Services::OwsAccounting.report_type_matcher(@selected_report_type)
    periods = Support::Services::OwsAccounting.periods_from_url(@browser.url)
    query = Support::Services::OwsAccounting.generate_query_get_report_url(
      file_type: @selected_report_file_type,
      number_format: number_format,
      report_format: report_format,
      periods: periods
    )

    @url = Support::Services::OwsAccounting.get_report_url(headers, query)

    report_url = URI.parse(@url)
    @downloaded_file_name = FileSystemHelpers::Downloader.download(report_url, with_timestamp: false).first
  end
end

When(/^I try to navigate to the next page$/) do
  on(Accounting::StatementsPage) do |page|
    page.wait_for_loading_bar_to_disappear
    page.pagination_element.wait_until(&:present?)
    page.pagination_element.lis.last.link.click
  end
end

When(/^I click 'View Requested' link for last period with positive revenue$/) do
  on(Accounting::StatementsPage) do |page|
    page.wait_until { page.request_report_elements.count >= 1 }
    page.click_on_link_with_positive_revenue
  end
end

Then(/^I should be redirected to the view requested page$/) do
  on(Accounting::ViewRequestedReports) do |page|
    page.wait_until(60) do
      page.current_url.include?("#{@selected_report_period}/history")
    end
    page.progress_bar_element.element.wait_while(timeout: 90, &:present?)
  end
end

Then(/^I should see all available reports that currently queued or ready for download$/) do
  on(Accounting::ViewRequestedReports) do |page|
    expected_note = "Available below are all reports currently queued or ready for download for this period."
    expected_table_header = ["DATE", "REQUESTED BY", "TRANSACTION TYPES",
                             "NUMBER FORMAT", "FILE TYPE", "STATUS"]
    actual_table_header = page.requested_report_table_element.ths.collect { |th| th.text }
    expect(page.note_paragraph).to eq(expected_note)
    expect(actual_table_header).to match_array(expected_table_header)
    expect(page.requested_report_table_element.count >= 2).to be true
    @report_period = page.page_header.split(" ").last(2).join
  end
end

Then(/^the ViewRequestedReports page title should be displayed correctly$/) do
  on(Accounting::ViewRequestedReports) do |page|
    expected_page_header = "Requested Reports for #{page.url.scan(/\w+_\d+/).first.tr('_', ' ')}"
    expect(page.page_header).to eq(expected_page_header)
  end
end

When(/^I try to download report file$/) do
  on(Accounting::ViewRequestedReports) do |page|
    last_report_details = page.report_details(page.reports_elements.first)
    @selected_report_number_format ||= last_report_details[:number_format]
    @selected_report_file_type ||= last_report_details[:file_type]
    @selected_report_type ||= last_report_details[:report_type]

    @accounting_user ||= @users.accounting_user
    headers = Support::Services::OwsAccounting.generate_headers(@accounting_user)
    number_format = Support::Services::OwsAccounting.number_format_matcher(@selected_report_number_format)
    report_format = Support::Services::OwsAccounting.report_type_matcher(@selected_report_type)
    periods = Support::Services::OwsAccounting.periods_from_url(@browser.url)
    query = Support::Services::OwsAccounting.generate_query_get_report_url(
      file_type: @selected_report_file_type,
      number_format: number_format,
      report_format: report_format,
      periods: periods
    )

    @url = Support::Services::OwsAccounting.get_report_url(headers, query)

    report_url = URI.parse(@url)
    @downloaded_file_name = FileSystemHelpers::Downloader.download(report_url, with_timestamp: false).first
  end
end

When(/^I view the accounting breakdown for "([^\"]*)" to "([^\"]*)"$/) do |first, last|
  on(Workstation::AccountingBreakdownPage) do |page|
    page.first_period = first
    page.last_period = last
    page.apply_period
    page.wait_for_spinner_to_disappear
    puts "current period url: #{page.current_url}"
  end
end

Then(/^I should see a (.*?) publishing deduction of "([^\"]*)"$/) do |type_of_deduction, expected|
  on(Workstation::AccountingBreakdownPage) do |page|
    # Rightmost column should be currency amount:
    actual = page.send(type_of_deduction.to_snake_case.to_s)
    puts "value on page: #{actual}"
    expect(actual).to eq(expected)
  end
end

Then(/^I should see an Outstanding Balance of "([^\"]*)"$/) do |expected|
  on(Workstation::AccountingBreakdownPage) do |page|
    actual = page.outstanding_balance
    puts "value on page: #{actual}"
    expect(actual).to eq(expected)
  end
end

Given(/^I am on the accounting breakdown page for the current period$/) do
  on(Workstation::AccountingBreakdownPage) do |page|
    page.goto unless page.current_url.include? "expense_view_by"
    page.wait_for_spinner_to_disappear
    puts "current period url: #{page.current_url}"
  end
end

When(/^I view the accounting breakdown for the current period through the Accounting Snapshot$/) do
  # Use the link in the Accounting Snapshot
  on(ReactWorkstation::ReactHomePage) do |page|
    page.wait_until(60) do
      page.accounting_period_link_elements.last && page.accounting_period_link_elements.last.present?
    end
    @snapshot_period = page.accounting_period_name_elements[-1].text
    puts "current period name: #{@snapshot_period}"
    @snapshot_revenue = page.accounting_period_link_elements[-1].text
    puts "current period revenue: #{@snapshot_revenue}"
    page.accounting_period_link_elements[-1].click
    puts "current period url: #{page.current_url}"
  end
end

Then(/^the start and end period filters should be correct$/) do
  on(Workstation::AccountingBreakdownPage) do |page|
    page.wait_for_spinner_to_disappear
    puts "first_period filter: #{page.first_period}"
    puts "last_period filter: #{page.last_period}"
    expect(@snapshot_period.split[0].downcase).to include(page.first_period.split[0].downcase)
    expect(@snapshot_period.split[1]).to eq(page.first_period.split[1])
  end
end

Then(/^the Revenue should match the value in the snapshot$/) do
  on(Workstation::AccountingBreakdownPage) do |page|
    page.wait_for_statement_table
    case @gross_revenue
    when "enabled"
      revenue = page.gross_revenue
      puts "revenue on breakdown page: #{revenue}"
      expect(revenue).to eq(@snapshot_revenue)
    when "control"
      expect(page.gross_revenue_element.exists?).to be false
    end
  end
end

# rubocop:disable Metrics/BlockLength
Then(/^I should see the correct Outstanding Balance$/) do
  # Do summary section computation
  on(Workstation::AccountingBreakdownPage) do |page|
    page.wait_for_statement_table
    opening_bal = page.opening_balance
    adv_payment = page.advance_paid if page.advance_paid?
    revenue = page.revenue
    performance_rights = page.performance_rights if page.performance_rights?
    compilations = page.compilations if page.compilations?
    sync_licensing = page.sync_licensing if page.sync_licensing?
    full_tracks = page.full_tracks if page.full_tracks?
    itunes_match = page.itunes_match if page.itunes_match?
    ringtones = page.ringtones if page.ringtones?
    encoding_fees = page.encoding_fees if page.encoding_fees?
    adjustments = page.adjustments if page.adjustments?
    payment = page.payment

    # Convert to a bigdecimal in US number format, stripping any non-digit chars,
    # 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_bal if opening_bal
    running_total += c.call adv_payment if adv_payment # Adding because this is a negative value in the UI
    running_total += c.call revenue if revenue
    running_total += c.call performance_rights if performance_rights
    running_total += c.call compilations if compilations
    running_total += c.call sync_licensing if sync_licensing
    running_total += c.call encoding_fees if encoding_fees
    running_total += c.call full_tracks if full_tracks
    running_total += c.call itunes_match if itunes_match
    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 page.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)
  end
end
# rubocop:enable Metrics/BlockLength

When(/^I apply the new (.*?) filter to the accounting breakdown$/) do |filter|
  on Workstation::AccountingBreakdownPage do |page|
    page.wait_for_spinner_to_disappear
    page.wait_until { page.choose_accounting_filter? }
    page.remove_filter if page.remove_filter?
    page.choose_accounting_filter_element.click
    page.click_new_filter_element(filter)
    page.filter_select_element.click
    page.search_for_product_breakdown if filter == "product"
    page.filter_select_element.link_element.when_present(90).click
  end
end

Then(/^I should either see a DRB Revenue Total or a "no accounting information" message$/) do
  on Workstation::AccountingBreakdownPage do |page|
    page.wait_until(120) do
      page.no_data_element.element.present? ||
        page.breakdown_table_element.element.present?
    end
    puts "no data seen!" if page.no_data?
    puts "breakdown table seen!" if page.breakdown_table?
  end
end

Then(/^the new moved filters? should show as applied (.*?)$/) do |filter|
  actual_filter = on(Workstation::AccountingBreakdownPage).filter_selected
  puts "actual filter: #{actual_filter}"
  puts "expected_filter: #{filter}"
  expect(actual_filter.downcase).to include filter
end

Then(/^I should be able to clear each filter$/) do
  on Workstation::AccountingBreakdownPage do |page|
    page.wait_for_spinner_to_disappear
    puts "original number of filters: #{page.applied_filter_div_elements.size}"
    page.clear_filter_elements.each(&:click)
    final_applied_filters = page.applied_filter_div_elements.size
    has_no_filters = page.no_filters?
    puts "final number of filters applied: #{final_applied_filters}"
    puts "no filters? #{has_no_filters}"
    expect(final_applied_filters).to eql 0
    expect(has_no_filters).to be true
  end
end

When(/^I apply an? (.*?) view to the accounting breakdown$/) do |view_text|
  @chosen_view = view_text.to_snake_case
  on Workstation::AccountingBreakdownPage do |page|
    puts "view before click: #{page.active_view_element.element.text}"
    page.send("#{@chosen_view}_view")
    page.wait_until { page.send("#{@chosen_view}_view_element").class_name.include? "active" }
    expect(page.active_view_element.element.text.downcase).to eql view_text
  end
end

Then(/^the DRB Revenue Total should match the Summary section Revenue$/) do
  on Workstation::AccountingBreakdownPage do |page|
    page.wait_until { page.breakdown_table? }
    drb_revenue = page.breakdown_revenue
    puts "DRB revenue total: #{drb_revenue}"
    summary_revenue = page.revenue
    expect(drb_revenue).to eq(summary_revenue)
  end
end

Then(/^the view should show as applied$/) do
  on Workstation::AccountingBreakdownPage do |page|
    puts "expected view: #{@chosen_view}"
    expect(page.active_view_element.class_name).to eq(page.send("#{@chosen_view}_view_element").class_name)
  end
end

Then(/^I should see the (\S+) column$/) do |column_name|
  on(Workstation::AccountingBreakdownPage) do |page|
    expect(page.column_exists?(column_name)).to be true
  end
end

Given(/^I am on the accounting breakdown page for the penultimate period$/) do
  visit(Workstation::AccountingBreakdownPage) do |page|
    page.wait_for_spinner_to_disappear
    penultimate_period_name = page.first_period_options[1]
    page.first_period = penultimate_period_name
    page.last_period = penultimate_period_name
    page.apply_period
    page.wait_for_spinner_to_disappear
    page.wait_for_statement_table
  end
end

When(/^I get the penultimate period's Opening Balance$/) do
  on(Workstation::AccountingBreakdownPage) do |page|
    @penultimate_opening = page.opening_balance
    puts "value on page: #{@penultimate_opening}"
  end
end

Then(/^the antepenultimate period's Outstanding Balance should match it$/) do
  on Workstation::AccountingBreakdownPage do |page|
    antepenultimate_period_name = page.first_period_options[1]
    page.first_period = antepenultimate_period_name
    page.last_period = antepenultimate_period_name
    page.apply_period
    page.wait_for_spinner_to_disappear
    page.wait_for_statement_table
    antepenultimate_outstanding = page.outstanding_balance
    puts "value on page: #{antepenultimate_outstanding}"
    expect(antepenultimate_outstanding.delete!("£").to_f)
      .to be_within(0.01).of(@penultimate_opening.delete("£").to_f)
  end
end

When(/^I view the (.*?) pop\-over$/) do |adjustment_type|
  on(Workstation::AccountingBreakdownPage) do |page|
    page.wait_for_spinner_to_disappear
    page.click_adjustment_details_link(adjustment_type)
    page.wait_until { page.adjustments_pop_over? }
  end
end

Then(/^the sum of the individual statements should be equal to the (.*?) total$/) do |adjustment_type|
  on(Workstation::AccountingBreakdownPage) do |page|
    current_adjustment = page.send(adjustment_type.to_snake_case)
    expect(page.adjustments_sum).to be_within(0.05).of(page.currency_to_bigdecimal(current_adjustment))
    page.click_adjustment_details_link(adjustment_type)
    page.wait_until { !page.adjustments_pop_over? }
  end
end

Then(/^I confirm that the added adjustment is present$/) do
  added_adjustment = DataHelpers::UploadManualAdjustment.records.last["comment"]
  on(Workstation::AccountingBreakdownPage) do |page|
    expect(page.adjustment_comment_elements.any? { |y| y.text.include? added_adjustment }).to be true
  end
end

Then(/^I should not see any manual adjustment data$/) do
  on(Workstation::AccountingBreakdownPage) do |page|
    expect(
      [
        page.performance_rights?,
        page.compilations?,
        page.sync_licensing?,
        page.adjustments?
      ]
    ).to all(be false)
  end
end

Given(/^we aren't in the middle of an accounting run$/) do
  fail(
    "Currently in the middle of an accounting run!"
  ) if Support::Helpers::AccountingRun.in_progress?
end

When(/^I navigate to the breakdown page for the previous period from the statements page$/) do
  on Workstation::AccountingStatementsPage do |page|
    page.wait_for_loading_bar_to_disappear
    page.wait_until { !page.statement_table_element[3].nil? }
    statement_raw = page.statement_table_element[3]
    @statement_previous_period = statement_raw["PERIOD"].text
    @statement_previous_revenue = statement_raw["REVENUE"].text.gsub(/[^\d\.-]/, "").to_f
    page.wait_until { page.payment_from_row(3) > 0.0 }
    @statement_previous_payment = page.payment_from_row(3)
    statement_raw["BREAKDOWN"].click
  end
end

Then(/^I should see the accounting breakdown page for the selected previous period$/) do
  on(Workstation::AccountingBreakdownPage) do |page|
    Retriable.retriable(on: [RSpec::Expectations::ExpectationNotMetError], tries: 2, base_interval: 5) do
      page.wait_for_spinner_to_disappear
      first_period = page.first_period
      expect(@statement_previous_period).to eq(first_period)
      puts "statement previous period #{@statement_previous_period}"
      puts "breakdown first period #{first_period}"
      last_period = page.last_period
      expect(@statement_previous_period).to eq(last_period)
      puts "breakdown last period #{last_period}"
      case @gross_revenue
        # regex removes currency symbol from a value to make it a simple float
      when "enabled"
        revenue = page.gross_revenue.gsub(/[^\d\.-]/, "").to_f
        puts "statement previous revenue #{@statement_previous_revenue}"
        puts "breakdown revenue #{revenue}"
        expect(@statement_previous_revenue).to eq(revenue)
      when "control"
        expect(page.gross_revenue_element.exists?).to be false
      end
      # regex removes currency symbol from a value to make it a simple float
      payment = page.payment.gsub(/[^\d\.]/, "").to_f
      puts "statement previous payment #{@statement_previous_payment}"
      puts "breakdown payment #{payment}"
      expect(@statement_previous_payment).to eq(payment)
    end
  end
end

When(/^Gross Revenue logic is (.*?)$/) do |state|
  @gross_revenue = state
end

When(/^I select (.*) file type$/) do |file_type|
  on(Accounting::RequestReportPage) do |page|
    @selected_report_file_type = file_type
    page.on_label(file_type).click
  end
end

When(/^I clean up previous downloads history for (.*) report$/) do |report_type|
  @accounting_user ||= @users.accounting_user
  on(Accounting::RequestReportPage) do
    @selected_report_period = @browser.url.scan(/\d\d\d/).last
    number_format = @selected_report_number_format == "US" ? "en_US" : "es_ES"

    user_id_type = if @accounting_user_type == :sub
                     "#{@accounting_user.info[:id]}S"
                   else
                     "#{@accounting_user.info[:id]}L"
                   end
    params = {
      period_id: @selected_report_period,
      user_id_type: user_id_type,
      file_type: @selected_report_file_type,
      number_format: number_format,
      report_type: report_type
    }
    DataHelpers::AccountingDBCleaner.new.clean_up(params)
  end
end

When(/^I select (.*) number format$/) do |number_format|
  on(Accounting::RequestReportPage) do |page|
    @selected_report_number_format = number_format
    number_format_label = number_format == "US" ? "en_#{number_format}" : "es_ES"
    page.on_label(number_format_label).click
  end
end

Then(/^the last report should be displayed correctly on the requested reports history page$/) do
  on(Accounting::ViewRequestedReports) do |page|
    expect(page.alert_msg).to eq("You will receive an email when your report is ready for download.")
    page.wait_for_progress_bar
    last_report_details = page.report_details(page.reports_elements.first)
    if @selected_report_type == "custom"
      expect(last_report_details[:transaction_types]).to eq(@expected_transaction_type)
    end
    expect(Date.parse(last_report_details[:date])).to eq(Date.today)
    expect(last_report_details[:number_format]).to eq(@selected_report_number_format)
    expect(last_report_details[:file_type]).to eq(@selected_report_file_type)
    expect(last_report_details[:status]).to eq("In Progress").or eq("Download")
  end
end

Then(/^I wait until the report has Download link$/) do
  on(Accounting::ViewRequestedReports) do |page|
    eventually(timeout: 240, interval: 2) do
      @browser.refresh
      page.wait_until { page.reports_elements.any? }
      expect(page.reports_elements.first.text).to include("Download")
    end
  end
end

When(/^I try to download file from the last generated report$/) do
  on(Accounting::ViewRequestedReports) do |page|
    @report_period = page.page_header.split(" ").last(2).join
    headers = Support::Services::OwsAccounting.generate_headers(@accounting_user)
    number_format = Support::Services::OwsAccounting.number_format_matcher(@selected_report_number_format)

    if @selected_report_type == "custom"
      report_format = @expected_transaction_type.delete(" ")
    else
      report_format = Support::Services::OwsAccounting.report_type_matcher(@selected_report_type)
    end

    periods = Support::Services::OwsAccounting.periods_from_url(@browser.url)
    query = Support::Services::OwsAccounting.generate_query_get_report_url(
      file_type: @selected_report_file_type,
      number_format: number_format,
      report_format: report_format,
      periods: periods
    )

    file_url = Support::Services::OwsAccounting.get_report_url(headers, query)
    @downloaded_file_name = FileSystemHelpers::Downloader.download(file_url, with_timestamp: false).first
  end
end

Then(/^the report file should have required fields$/) do
  expected_headers = DataHelpers::AccountingReportData.new.expected_headers(@selected_report_type,
                                                                            @accounting_user_type)
  @report_content = DataHelpers::AccountingReportData.new.read_report_file(@downloaded_report_file)
  report_headers = if @selected_report_file_type == "xls"
                     # The first symbol in XLS table is unwanted
                     @report_content.first[1..-1].split("\t")
                   else
                     @report_content.first.split("\t")
                   end
  expect(report_headers).to match_array(expected_headers)
end

Then(/^I should have downloaded file in the system with corresponding name$/) do
  @accounting_user ||= @users.accounting_user
  unzipped_files = DataHelpers::AccountingReportData.new.extract_zip(@downloaded_file_name)
  expect(unzipped_files.count).to eq(1),
                                  "Expected '#{@downloaded_file_name}'.zip to contain only one report file"
  @downloaded_report_file = unzipped_files.first
  label = @accounting_user.info[:vendor_name].gsub(/[!@#($%,)]/, "").downcase.tr(" ", "_")
  expect(@downloaded_report_file).to include(label)
  expect(@downloaded_report_file).to include(@report_period)
  expect(@downloaded_report_file).to include(@selected_report_number_format)
  expect(@downloaded_report_file).to include(@selected_report_file_type)
  expect(@downloaded_report_file).to include(@selected_report_type)
end

Then(/^I use (.*) accounting user$/) do |accounting_user|
  @accounting_user_type = accounting_user.downcase.to_sym
  @accounting_user = @users.accounting_user("accounting_#{@accounting_user_type}")
end

Then(/^I should see the Recent Revenue starting from "(.*)" period$/) do |period_name|
  on(ReactWorkstation::ReactHomePage) do |page|
    page.wait_until(60) do
      page.accounting_period_link_elements.last && page.accounting_period_link_elements.last.present?
    end
    expect(page.accounting_period_name_elements.first.text).to eq(period_name)
  end
end

Then(/^I should( not)? see "([^"]*)" tab in the subnavigation menu$/) do |flag, tab_name|
  on(Workstation::AccountingBreakdownPage) do |page|
    expect(page.subnav.include?(tab_name)).to eq(!flag),
                                              "subnav menu should#{flag} include '#{tab_name}'"
  end
end

When(/^I click on "([^"]*)" tab$/) do |tab_name|
  on(Workstation::AccountingBreakdownPage) do |page|
    page.subnav_element.link_element(text: tab_name).click
  end
end

Then(/^I should be redirected to the statements page Physical Reserves page$/) do
  expect(@browser.url).to include("/accounting/physicalreserves")
end

Then(/^I should see Expected Reserve Payouts table$/) do
  on(Workstation::AccountingPhysicalReservesPage) do |page|
    page.reserve_payouts_table_element.when_present
    expect(page.reserve_payouts_table_element.text.downcase).not_to include("no data found")

    reserve_payouts_data = page.reserve_payouts_data
    user_id = @users.accounting_user.info[:id]
    reserve_payouts_data.each do |payouts_data_row|
      period_id = DataHelpers::AccountingPeriodHelper.name_to_period_id(payouts_data_row[:reserve_taken])
      manual_adjustment = Support::Helpers::Queries.manual_adjustment(user_id, period_id)
      expect(payouts_data_row[:currency]).to eq("USD")
      expect(payouts_data_row[:amount].to_f).to eq(manual_adjustment["amount"].to_f.round(2))
      apply_to = Support::Helpers::Queries.accounting_period(manual_adjustment["apply_to_period_id"])
      apply_to_period_name = Date.parse("#{apply_to['year']}/#{apply_to['month']}").strftime("%b %Y")
      expect(payouts_data_row[:expected_release]).to eq(apply_to_period_name)
    end
  end
end
