Given(/^there is no audit information for ISRC (.*?)$/) do |isrc|
  on(MastersRegistry::BasePage) do |page|
    entries = page.entries_for_isrc(isrc)
    page.delete_all_entries(entries)
  end
end

And(/^I unlock every territory for (.*?)$/) do |isrc|
  visit(MastersRegistry::BulkLockTerritoriesPage) do |page|
    page.wait_until { page.isrcs? }
    page.isrcs = isrc
    page.select_lock_or_not "unlock"
    page.territories = "ww"
    page.submit
  end
end

Then(/^I can access the master rights registry app$/) do
  on(OA::RelationshipsPage).master_rights_registry
  on(MastersRegistry::MastersEditorPage) do |page|
    eventually(timeout: 30) do
      expect(page.isrc_field?).to be true
    end
    page.expect_to_be_on_page
  end
end

When(/^I lock territories(?: except (.*?))? for ISRCs?: (.*?)$/) do |territories, isrcs|
  @isrcs = isrcs.split(",").map(&:strip).join("\n")
  @reason = "reason #{Time.stamp}"
  @territory_list = territories.split(",").map(&:strip) unless territories.nil?
  on(MastersRegistry::BulkLockTerritoriesPage) do |page|
    page.isrcs_element.when_present
    page.isrcs = @isrcs
    page.select_all_these_or_except "except" unless territories.nil?
    page.territories = @territory_list.join(", ")
    page.reason = @reason
    page.submit
  end
end

Then(/^I see a message indicating that the bulk action process started$/) do
  on(MastersRegistry::BulkLockTerritoriesPage) do |page|
    page.wait_until { page.success_message? }
    expect(page.success_message_element.link_element.href).to include "bulk-actions-statuses"
  end
  @time_initiated = Support::Helpers::Timezone.current_browser_time(false).strftime("%b %d, %Y, %I:%M:%S %p")
end

Then(/^I expect to see a success for the last bulk lock action$/) do
  range_start = DateTime.parse(@time_initiated) - 0.0001
  range_end = DateTime.parse(@time_initiated) + 0.0001
  on(MastersRegistry::BulkActionStatusPage) do |page|
    refresh = proc do |exception, try|
      puts "#{exception.class}: '#{exception.message}' - Retries: #{try}"
      page.refresh
    end
    Retriable.retriable(on: Watir::Wait::TimeoutError, tries: 5, on_retry: refresh) do
      latest_bulk_action = page.find_latest_action(range_start, range_end)
      page.wait_until(5) { page.action_statuses_element[latest_bulk_action]["Status"].text == "Success" }
    end
  end
end

When(/^I search for ISRC: (.*?)$/) do |isrc|
  on(MastersRegistry::MastersEditorPage) do |page|
    page.isrc_field = isrc
    sleep 1
    page.search_button
  end
end

Then(/^I should be on the MastersRegistry::MastersEditorPage for ISRC (.*)$/) do |isrc|
  on(MastersRegistry::MastersEditorPage) do |page|
    page.ownership_panel_element.element.wait_until(&:present?)
    expect(page.query_value_from_current_url("isrc")).to eql isrc
  end
end

When(/^I am on MastersRegistry::MastersEditorPage for ISRC: (.*?)$/) do |isrc|
  @isrc = isrc
  visit MastersRegistry::MastersEditorPage, using_params: { queries: { "isrc" => @isrc } }
end

Then(/^I should see the territories locked for the reason$/) do
  on(MastersRegistry::MastersEditorPage) do |page|
    reason_title = page.locked_territories_section_element.p(text: @reason)
    reason_territories = reason_title.parent.parent.ps.last.text
    added_territories = []
    @territory_list.each { |territory| added_territories.push(page.convert_territory(territory)) }
    added_territories.each { |territory| expect(reason_territories).to include(territory) }
  end
end

Given(/^(.*?) are unclaimed$/) do |territories|
  @territory_list = territories.split(",").map(&:strip)
  territory_list = []
  on(MastersRegistry::MastersEditorPage) do |page|
    @territory_list.each { |territory| territory_list.push(page.convert_territory(territory)) }
    page.wait_until { page.unclaimed_territories_section? }
    page.show_all_elements.last.click until page.show_all_elements.empty?
    claimed_territories = territory_list - page.section_territories("Unclaimed")
    unless claimed_territories.empty?
      claimed_territories.each { |territory| page.remove_single_territory(territory) }
    end
    section = page.unclaimed_territories_section_element
    if section.link_element.element.present? && (section.link_element.text.include? "Show All")
      section.link_element.click
      page.wait_until do
        !section.p(class: "Territories-second-line").when_present.text.empty?
      end
    end
    expect(section.text).to include(*territory_list)
  end
end

When(/^I (add|lock|remove) (.*?) (to|from) the (.*?) section$/) do |add_or_remove, territories, _, ownership|
  on(MastersRegistry::MastersEditorPage).modify_territories(
    add_or_remove.to_sym,
    territories,
    ownership
  )
end

Then(/^(.*?) are added to the (.*?) list$/) do |territories, ownership|
  territories = territories.split(",").map(&:strip)
  territory_list = []
  on(MastersRegistry::MastersEditorPage) do |page|
    territories.each { |territory| territory_list.push(page.convert_territory(territory)) }
    page.show_all_elements.last.click until page.show_all_elements.empty?
    expect(page.section_territories(ownership)).to include(*territory_list)
    expect(page.section_territories("Unclaimed")).not_to include(*territory_list)
  end
end

Then(/^(.*?) become unclaimed$/) do |territories|
  territories = territories.split(",").map(&:strip)
  territory_list = []
  on(MastersRegistry::MastersEditorPage) do |page|
    territories.each { |territory| territory_list.push(page.convert_territory(territory)) }
    page.show_all_elements.last.click until page.show_all_elements.empty?
    expect(page.section_territories("Unclaimed")).to include(*territory_list)
  end
end

Given(/^every territory is unclaimed for the ISRC$/) do
  on(MastersRegistry::MastersEditorPage) do |page|
    page.wait_until { page.unclaimed_territories_section? }
    page.unclaim_all_territories
  end
end

When(/^I add a rightsholder for every territory(?: except (.*))?$/) do |territories|
  @tuid = Support::DbClient.query_art_relations(
    "SELECT id FROM track WHERE isrc = '#{@isrc}'"
  ).first["id"].to_s
  on(MastersRegistry::MastersEditorPage) do |page|
    page.add_new_rightsholder_element.when_present.click
    page.new_rightsholder_tuid_element.when_present.element.set @tuid
    if territories.nil?
      territories = "ww"
    else
      page.label_element(class: "RadioButton-label", text: "Claim all except these territories").click
    end
    page.new_rightsholder_territories = territories
    page.submit_rightsholder
    page.wait_until { page.success_message_element.when_present.text.include? "Rightsholder was added" }
  end
end

Then(/^every territory is claimed for the rightsholder$/) do
  on(MastersRegistry::MastersEditorPage) do |page|
    page.wait_until { page.rightsholders_section? }
    expect(page.rightsholders_section).to include @tuid
    expect(page.unclaimed_territories_section).to include "0 of 249 Total Territories"
  end
end

Then(/^(.*?) should be the only unclaimed territories$/) do |territories|
  territories = territories.split(",").map(&:strip)
  territory_list = []
  on(MastersRegistry::MastersEditorPage) do |page|
    page.wait_until { page.unclaimed_territories_section? }
    territories.each { |territory| territory_list.push(page.convert_territory(territory)) }
    page.show_all_elements.last.click until page.show_all_elements.empty?
    expect(page.section_territories("Unclaimed")).to match_array territory_list
  end
end

Then(/^I assert rights for a grouped conflict ID$/) do
  on(MastersRegistry::ExternalConflictsPage) do |page|
    page.conflicts_element.when_present.set "16957456|2014-07-23|Believe Music|assert"
    page.select_status "orchard_asserted"
    page.update_conflict_status
  end
end

Then(/^I see that rights were updated for the grouped conflict ID$/) do
  on(MastersRegistry::ExternalConflictsPage) do |page|
    eventually do
      expect(page.successful_update_element.when_present.text).to include "updated to Orchard Asserted"
    end
  end
end

When(/^I attempt to update track rights for UPC: (.*?)$/) do |upc|
  on(MastersRegistry::BulkUpdateUPCsPage) do |page|
    page.upcs_field = upc
    page.submit
  end
end

When(/^I should see an (.*) for an (.*?)$/) do |message, upc_type|
  on(MastersRegistry::BulkUpdateUPCsPage) do |page|
    page.generic_element.wait_until(&:present?)
    case upc_type
    when "valid"
      expect(page.success_message_element.text).to include message
    else
      expect(page.error_message_elements[1].text).to include message
    end
  end
end
