When(/^I generate a label audit report for label (\d+)/) do |label_id|
  visit(OA::ViewVendorPage, using_params: { queries: { "vendor_id" => label_id } }).youtube_audit_beta
  on(OA::YouTubeLabelAuditPage) do |page|
    page.wait_for_audits
    # If the button is disabled, verify that one has already been
    # requested/in progress. Otherwise, generate a new one.
    if page.generate_audit_prep_doc_element.disabled?
      expect(page.audits_table_element[1]["Status"].text).to eq("in_progress").or eq("requested")
    else
      page.generate_audit_prep_doc
      @generating = true
    end
  end
end

Then(/^I should see a confirmation message and the report queued for processing/) do
  # Skip the generation verification if one is currently in progress
  if @generating
    on(OA::YouTubeLabelAuditPage) do |page|
      expect(page.confirmation_message_element.when_present.text).to eq "Initiated new audit."
      expect(page.audits_table_element[1]["Status"].text).to eq "requested"
    end
  else
    puts "Report generation was skipped for this session."
  end
end

Then(/^I download the latest label audit report for label (\d+)/) do |label_id|
  visit(OA::ViewVendorPage, using_params: { queries: { "vendor_id" => label_id } }).youtube_audit_beta
  on(OA::YouTubeLabelAuditPage) do |page|
    page.wait_for_audits
    if page.no_audits_element.element.present?
      puts "No audits have been generated for this label yet."
    else
      # Fail if the latest date is earlier than today's date and it still hasn't finished processing
      fail "Label audit hasn't finished processing in over a day." if page.report_requested_over_a_day_ago?
      # If there's a completed report available, download it. Otherwise, print the latest report's status
      if page.audits_table_element.cell_elements.any? { |cells| cells.text == "complete" }
        complete_row_index = page.audits_table_element.find_index do |rows|
          rows["Status"].text == "complete"
        end
        download_url = page.audits_table_element[complete_row_index]["Audit Prep Doc"].link_element.href
        @downloaded_file = FileSystemHelpers::Downloader.download(download_url, with_timestamp: false).first
        @label_id = label_id
      else
        latest_report_status = page.audits_table_element[1]["Status"].text
        puts "Reports are still processing: The latest report has a status of \"#{latest_report_status}\""
      end
    end
  end
end

Then(/^I see the label audit report as a spreadsheet with the appropriate sections/) do
  # If a report is available, verify that the headers for the report are correct and that the
  # label ID matches
  if @downloaded_file.nil?
    puts "No label audit reports are ready for viewing."
  else
    report = CSV.open(@downloaded_file)
    expected_headers = DataHelpers::LabelAudit.new.report_headers
    report_headers = report.first
    expect(report_headers).to match_array(expected_headers)
    expect(report.first[0]).to eq @label_id
  end
end
