And(/^I clear the artist data, if it exists$/) do
  on(OA::ViewReleasePage) do |page|
    page.manage_artist
    page.delete_first_artist until page.no_artist?
  end
end

When(/^I set values for new artist and save the values$/) do
  on(OA::ViewReleasePage) do |page|
    @artist_name_add = "TestArtistAdd#{Time.stamp}"
    @artist_role_add = "Producer"
    page.artist_name_elements[0].value = @artist_name_add
    page.select_role_elements[0].select(@artist_role_add)
    page.add_artist
  end
end

Then(/^I update the values in newly added artist$/) do
  on(OA::ViewReleasePage) do |page|
    @artist_name_update = "TestArtistUpdate#{Time.stamp}"
    @artist_role_update = "Conductor"
    page.artist_name_elements[0].value = @artist_name_update
    page.select_role_elements[0].select(@artist_role_update)
    page.update_artists_elements[0].click
  end
end

And(/^I remove the newly added artist artist$/) do
  on(OA::ViewReleasePage) do |page|
    page.delete_first_artist
  end
end

And(/^I should be able to see the (new|updated) values$/) do |action|
  on(OA::ViewReleasePage) do |page|
    case action
    when "new"
      artist_name = @artist_name_add
      artist_role = @artist_role_add.downcase
      message = "Release artist successfully created."

    when "updated"
      artist_name = @artist_name_update
      artist_role = @artist_role_update.downcase
      message = "Release artist successfully updated."
    end
    page.wait_until { page.artist_name_elements.any? }
    eventually { expect(page.artist_name_elements[0].value).to eq artist_name }
    page.wait_until { page.select_role_elements.any? }
    eventually { expect(page.select_role_elements[0].value).to eq artist_role }
    print_tries = proc do |exception, try|
      puts "#{exception.class}: '#{exception.message}' - Retry attempt: #{try}"
      sleep 1
    end
    Retriable.retriable(on: Selenium::WebDriver::Error::UnknownError, tries: 3, on_retry: print_tries) do
      eventually { expect(page.confirmation_message_element.text).to eql message }
    end
  end
end

Then(/^I should check values are not present$/) do
  on(OA::ViewReleasePage) do |page|
    delete_message = "Release aritst successfully deleted"
    eventually { expect(page.confirmation_message_element.text).to eql delete_message }
    expect(page.no_artist?).to be true
  end
end
