# Require runtime dependencies
require "envied"
require "phantomjs" # path helper
require "page-object"
require "rspec/expectations"
require "watir-webdriver"

# Require dev dependencies inside a begin statement
begin
  require "byebug"
rescue LoadError # rubocop:disable Lint/HandleExceptions
  # byebug is not a runtime dependency!
end

# Require support files used by this file
# Note that the support dir is autoloaded by Cucumber after this file
require_relative "helpers"
require_relative "project"

ENVied.require(:default) # Ensure environment variables are set, see Envfile

# Set the path to phantomjs.exe
Selenium::WebDriver::PhantomJS.path = Phantomjs.path

# Workaround for outdated version captive page
USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)"\
             " Chrome/33.0.1750.117 Safari/537.36"
capabilities = Selenium::WebDriver::Remote::Capabilities.phantomjs("phantomjs.page.settings.userAgent" => USER_AGENT)

# Initialize browser once
if ENVied.BROWSER == "phantomjs"
  browser = Watir::Browser.new(:phantomjs, desired_capabilities: capabilities)
else
  browser = Watir::Browser.new(ENVied.BROWSER.to_sym) # for local testing in a non-phantomjs browser (e.g. chrome)
end

# Register hooks
Before do
  @browser = browser
end

After do |scenario|
  begin
    if ENVied.SAVE_PNG
      # Note that saving screenshots as a file & linking in a json report is broken on cucumber 2.0.0:
      # This should only be used when testing locally, if at all...
      Dir.chdir(Project.root.join("build")) do # cd to where html is outputted
        prefix = scenario.failed? ? "FAILED" : "PASSED"
        stamp = Time.now.strftime("%s6%N")
        screenshot = "#{prefix}_#{scenario.name.gsub(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}_#{stamp}.png"
        browser.screenshot.save(screenshot)
        embed(screenshot, "image/png")
      end
    else
      # Take a screenshot, embed in the json report
      encoded_img = browser.driver.screenshot_as(:base64)
      embed("#{encoded_img}", "image/png;base64")
    end

  rescue Selenium::WebDriver::Error::UnknownError, Selenium::WebDriver::Error::WebDriverError
    Kernel.puts "Failed to take a screenshot for scenario #{scenario.name}! Continuing with the next test..."
  end
end

at_exit do
  browser.close
end

World(
  PageObject::PageFactory, # So we can use #visit and #on in Step Definitions
  Helpers # Convenience methods, ref: http://pivotallabs.com/cucumber-step-definitions-are-not-methods/
)

# Set default timeout for chained #when_present calls
PageObject.default_page_wait = 30
PageObject.default_element_wait = 30
