module World
  module StepHelpers
    # This step is useful for dismissing any dirty prompts raised on navigation
    # away from the last page in the previous scenario.
    def visit_and_dismiss_alerts(*args, &block)
      @browser.after_hooks.without do
        visit(*args)
        if @browser.alert.exists?
          puts "Encountered JS alert on navigation!"
          @browser.alert.ok if @browser.alert.exists?
        end
        on(*args, &block)
      end
    end

    def login_to_oa_with_valid_token(oa_user_data)
      login_helper = Support::Helpers::TwoFactorLogin.new(oa_user_data)

      # Browsers running in parallel can't go through the normal TFA workflow of
      # attempting to login, reading the email with the new token, and
      # following the link, because they will accidentally use each
      # other's tokens. Instead, let's manually create new tokens for each
      # thread when needed.
      secret = login_helper.create_new_secret
      visit(
        OA::VerifyPage,
        using_params: {
          queries: {
            secret: secret,
            login: oa_user_data[:username]
          }
        }
      )
      check_for_login_error
    end

    # Note that #World() includes private methods for some reason. If this
    # causes a problem, then you can remove this from World and turn it into a
    # class instead.

    private

    def check_for_login_error
      Watir::Wait.until do
        on(OA::BasePage).logout_link? || on(OA::LoginPage).message_text?
      end
      fail(
        "Login with token was unsuccessful! This is likely due to a race"\
        " condition with a browser running in parallel on OA."
      ) if on(OA::LoginPage).message_text?
    end
  end
end
