module Rspec::Dunlop::AuthenticationSupport

  # Add support for:
  #   visit WorkflowInstance.last
  def visit(*args)
    case args[0]
    when ActiveRecord::Base, Array, Class
      args[0] = polymorphic_path(args[0])
    end
    super *args
  end

  def i_am_logged_in_as_user(*user_args)
    if user_args.last.is_a?(Hash)
      user_args[-1][:role_names] = Array.wrap(user_args[-1][:role_names]) | ['read-class-WorkflowInstance'] if user_args[-1][:role_names].present?
    end
    @user = FactoryBot.create(:user, *user_args)
    i_am_logged_in_as(@user)
  end

  def i_am_logged_in_as_user_of_service_provider
    @service_provider ||= FactoryBot.create  :service_provider, :all_scenarios
    @user = FactoryBot.create(:user, service_provider: @service_provider)
    i_am_logged_in_as(@user)
  end

  def i_am_logged_in_as_admin
    @user = FactoryBot.create(:admin)
    i_am_logged_in_as(@user)
  end

  def current_user
    @user
  end

  def i_am_logged_in_as(user)
    visit new_user_session_path
    fill_in 'Email', with: user.email
    fill_in 'Password', with: user.password
    click_button 'Log in'
    #expect(current_path).to eq root_path
  end

  def screenshot
    screenshot_and_open_image
  end

  def open_page
    save_and_open_page
  end

  def submit_form
    find('input[type="submit"]').click
  end

  def submit_collection_form
    find('#new_collection input[type="submit"]').click
  end
end
