When(/^I go to the physical product territories section$/) do
  on(Project::PhysicalProductDetailsPage) do |page|
    sleep 2 # no idea why this is necessary
    page.navigate_to_territories_element.click
  end
  on(Project::ProductTerritoryRestrictionsPage).territories_list_element.when_present
end

When(/^I move all territories to cleared for sale$/) do
  on(Project::ProductTerritoryRestrictionsPage) do |page|
    page.clear_all_restricted_continents
  end
end

When(/^I move the continent (.*) to NOT cleared for sale$/) do |continent|
  on(Project::ProductTerritoryRestrictionsPage) do |page|
    page.check_cleared_continent(continent)
    page.restrict_selected_territories_element.click
  end
end

When(/^I move the (.*) country (.*) to cleared for sale$/) do |continent_adjective, country|
  continent = case continent_adjective
              when "European"
                "Europe"
              else
                fail "unknown continent!"
              end

  on(Project::ProductTerritoryRestrictionsPage) do |page|
    page.check_restricted_country(continent: continent, country: country)
    page.clear_selected_territories_element.click
  end
end

Then(
  /^I see (\d+) territories NOT cleared for sale on the territory restrictions page$/
) do |number_of_territories|
  on(Project::ProductTerritoryRestrictionsPage) do |page|
    expect(
      page.number_of_restricted_territories
    ).to eql(
      number_of_territories.to_i
    )
  end
end

When(/^I save the physical product territories$/) do
  on(Project::ProductTerritoryRestrictionsPage).physical_save_and_continue
  on(Project::ProductArtworkPage).artwork_section_element.when_present
end

When(/^I save the digital product territories$/) do
  on(Project::DigitalProductBasePage).save
end

Then(/^I see (\d+) territories NOT cleared for sale on the product review page$/) do |number_of_territories|
  on(Project::PhysicalProductReviewPage) do |page|
    page.territory_restriction_section_element.when_present
    expect(page.territory_restriction_elements.count).to eql number_of_territories.to_i
  end
end

Then(
  /^I see (\d+) territories NOT cleared for sale on the digital product overview page$/
) do |expected_number_of_territories|
  on(Project::DigitalProductOverviewPage) do |page|
    page.territory_restriction_section_element.when_present
    actual_restricted_territories = page.restricted_territories.split(", ")
    expect(actual_restricted_territories.count).to eql expected_number_of_territories.to_i
  end
end
