# rubocop:disable Metrics/BlockLength
Then(/^I delete all releases matching the term '(.*?)'$/) do |search_term|
  # WARNING: This should not be used in a scenario, as there is an extra-long wait.
  # This should only be kicked off manually.
  until on(Workstation::ReleaseBuilderPage).no_results_found
    selected_releases = []

    on Workstation::ReleaseBuilderPage do |page|
      releases_on_page = page.manage_releases_table_element.checkbox_elements.count
      (1..releases_on_page).each do |i|
        selected_releases.push(page.release_row(i).cell_elements[1].link_element.element.text)
      end
      page.select_all_link
      page.deactivated_delete_releases_button_element.element.wait_while(&:present?)
      page.delete_releases_button
      page.confirm_delete_releases_button_element.when_present.element.click
      # Extra-long waiting is used here in the event that a scenario uses this as a cleanup step
      # Example: Searching for 'watir' using label '7123' would return
      # multiple pages of results (prior to a recursive cleanup) and would
      # take a bit longer than usual to delete a long list of watir releases.
      begin
        page.deletion_in_progress_modal_element.element.wait_while(timeout: 120, &:present?)
      rescue Net::ReadTimeout
        page.confirm_delete_releases_button_element.element.wait_while(timeout: 120, &:present?)
      end
      puts "Deleted releases: #{selected_releases.join(', ')}"
      # retries step in case there's more than one page of matching results
      visit(Workstation::ReleaseBuilderPage, using_params: {
              queries: {
                "filterType" => "delivered,submitted,in_progress,error_correction,rejected",
                "productType" => "1,2,3,5",
                "releaseDate" => "desc",
                "name" => search_term
              }
            })
    end
    # Sets @@reusable_release to nil so other scenarios don't go to deleted releases
    Workstation::ViewReleasePage.reusable_release = nil
  end
  puts "No releases to delete"
end
# rubocop:enable Metrics/BlockLength

Given(/^I have data for the most recent check for label (\d+)$/) do |label_id|
  visit(OA::CheckPayableResultsPage, using_params: { queries: { "vendor_id" => label_id } }) do |page|
    check = page.most_recent_check
    payee = check["Label"].text
    check_no = check["Check No."].text.gsub("+ ", "")
    date = check["Cut Date"].text
    balance = check["Check Amount"].text
    @check = { label_id: label_id, payee: payee, check_no: check_no, balance: balance, date: date }
  end
end

Given(/^I am logged in to OA on production with personal credentials$/) do
  oa_prod_user = ENV["OA_PROD_USER"]
  oa_prod_pass = ENV["OA_PROD_PASS"]
  unless oa_prod_user && oa_prod_pass
    fail "must supply personal OA username and password as OA_PROD_USER and OA_PROD_PASS!"
  end
  if DOMAINS[:oa].include? "qaorch"
    fail "#{DOMAINS[:oa]} is not a production environment! set OA to the correct environment."
  end
  visit(OA::LoginPage).login_with oa_prod_user, oa_prod_pass
end

When(/^I update a release title with a unique string$/) do
  @new_name = Time.now.strftime("%s")
  @identifier = 888_831_100_782 # upc
  @etl_string = "http://search-prod-etl-releases-w2r3tsng5u43nyhapqbnmpuboe"\
  ".us-east-1.cloudsearch.amazonaws.com/2013-01-01/search?q=#{@identifier}"\
  "&return=release_name&sort=_score+desc&size=1&q.options"\
  "=%7B%22defaultOperator%22:%22and%22,%22fields%22:%5B%22upc%22%5D,"\
  "%22operators%22:%5B%5D%7D"

  puts "new name: #{@new_name}"
  visit(OA::EditReleasePage, using_params: { queries: { "upc" => @identifier } }) do |page|
    page.release_name = @new_name
    page.submit
    expect(page.green_confirmation_message?).to be true
  end
end

When(/^I update an artist name with a unique string$/) do
  @new_name = Time.now.strftime("%s")
  @identifier = 603_918 # artist id
  @etl_string = "http://search-prod-etl-artists-pzbekscb7bcvk7lntrggwiozam"\
  ".us-east-1.cloudsearch.amazonaws.com/2013-01-01/search?q=#{@identifier}"\
  "&return=artist_name&sort=_score+desc&size=1&q.options"\
  "=%7B%22defaultOperator%22:%22and%22,%22fields%22:%5B%22artist_id%22%5D,"\
  "%22operators%22:%5B%5D%7D"

  puts "new name: #{@new_name}"
  visit(OA::EditArtistPage, using_params: { queries: { "artist_id" => @identifier } }) do |page|
    page.artist_name = @new_name
    page.submit
    expect(page.green_confirmation_message?).to be true
  end
end

Then(/^The ETL endpoint returns the updated name$/) do
  start_time = Time.now
  interval = 5
  max_duration = 150

  @browser.goto @etl_string
  until @browser.text.include? @new_name
    fail "ETL didn't update in #{max_duration} seconds!" if Time.now - start_time > max_duration
    sleep interval
    @browser.refresh
  end
  duration = Time.now - start_time
  puts "ETL endpoint updated in #{duration - interval / 2} +/- #{interval} seconds"
end

Then(/^I can download audio for every track in the release$/) do
  on(OA::ViewReleasePage) do |page|
    page.download_track_elements.each do |element|
      element.link_element.click
    end
  end
  sleep 5
end
