require "benchmark"

module World
  module CodeHelpers
    # Usage example:
    #
    # I add the following to subaccount_transfer_tool_steps.rb:13:
    #
    #     bench { page.transfer_table_element['UPC'].text.split('UPC: ').last }
    #
    # When I run `cucumber features/subaccount_transfer_tool.feature LOCAL=t`
    # it gives me the following terminal output:
    #
    #               user     system      total        real
    # code:     0.040000   0.010000   0.050000 (  0.286190)
    #
    # And on the remote selenium node `cucumber features/subaccount_transfer_tool.feature REMOTE=t`
    #
    #               user     system      total        real
    # code:     0.050000   0.010000   0.060000 (  0.576539)
    def bench
      Benchmark.bm(7) do |x|
        x.report("code:") { yield }
      end
    end

    # rubocop:disable Lint/HandleExceptions
    def eventually(options = {})
      timeout = options[:timeout] || 30
      interval = options[:interval] || 0.1
      time_limit = Time.now + timeout
      loop do
        begin
          yield # will be what's in the block, eg. eventually(timeout: 60) { expect(thing1).to eq thing2 }
        rescue RSpec::Expectations::ExpectationNotMetError, Watir::Wait::TimeoutError,
               Watir::Exception::UnknownObjectException,
               Selenium::WebDriver::Error::StaleElementReferenceError => error
        end
        return if error.nil?
        fail error if Time.now >= time_limit
        sleep interval
      end
    end
    # rubocop:enable Lint/HandleExceptions
  end
end
