When(/^I am on the subtitles page for (\d+)$/) do |upc|
  @upc = upc.to_s
  visit(OA::LanguageAssetsPage, using_params: { upc: @upc })
end

Given(/^no subtitle or caption files are present$/) do
  on(OA::LanguageAssetsPage) do |page|
    page.sub_delete if page.sub_delete?
    page.caption_delete if page.caption_delete?
    puts "deleted subtitles and captions"
  end
end

And(/^I upload a caption file$/) do
  on(OA::LanguageAssetsPage) do |page|
    page.cc_track_number = "1"
    page.cc_file_input = File.join(Support::Paths.assets, "film_assets", "888003108349_English_Captions.scc")
    page.popup_screen_element.when_not_present
    expect(page.language_asset_table_element["Caption"]["Delete"].when_present(10).text).to eq("Delete")
  end
end

Given(/^I upload a subtitle file$/) do
  on(OA::LanguageAssetsPage) do |page|
    @wait_multiplier = page.check_rb_encoder_load("before uploading a subtitle file")
    page.track_number = "1"
    page.subtitle_file_input = File.join(
      Support::Paths.assets,
      "film_assets",
      "888003108318_Spanish_Subtitles.itt"
    )
    page.subtitle_language = "en-us"
    page.subtitle_upload_button
    expect(page.alert_confirmation_element.when_present(10).text).to include(
      "File has been successfully uploaded, and added to Queue to move to "\
      "storage."
    )
    fail page.alert_error if page.alert_error_element.element.present?
  end
end

Then(/^the new subtitle file should be uploaded and synced to QA$/) do
  visit(OA::AccessAssetPage) do |page|
    Timeout.timeout(180 * @wait_multiplier) do
      page.access_asset_type("subtitles itt", @upc, "QA")
      while page.asset_location_results_table.include?("No Data") ||
            page.asset_location_results_table_element[@upc]["Asset Status"].text == "N"
        page.refresh
      end
    end
    table_row = page.asset_location_results_table_element[@upc]
    expect(table_row[3].text).to eql "subtitles_itt"
    expect(table_row[2].text).to eql "QA"
    expect(table_row[4].text).to eql "Y"
  end
end

Then(/^the new caption file should be uploaded and synced to QA/) do
  visit(OA::AccessAssetPage) do |page|
    page.access_asset_type("caption", @upc, "Amazon S3")
    search_again = proc do |exception, try|
      puts "#{exception.class}: '#{exception.message}' - Retries: #{try}"
      page.goto
      page.access_asset_type("caption", @upc, "Amazon S3")
    end
    table_row = Retriable.retriable(on: NoMethodError, tries: 3, on_retry: search_again) do
      page.asset_location_results_table_element[@upc]
    end
    expect(table_row[3].text).to eql "caption"
    expect(table_row[2].text).to eql "Amazon S3"
  end
end
