require 'rails_helper'
require 'selenium/webdriver'

ENV['SMTP_SENDER'] = 'test@example.com'

if username = ENV['BS_USERNAME']
  password = ENV['BS_PASSWORD']

  Capybara.register_driver :browserstack do |app|
    cap = if ENV['BS_BROWSER']
      JSON.parse(ENV['BS_BROWSER'])
    else
      Selenium::WebDriver::Remote::Capabilities.firefox
    end

    ['device', 'browser_version'].each do |key|
      cap.delete(key) if cap[key].nil? && cap.is_a?(Hash)
    end

    cap['project'] = 'PVBE'
    cap['build'] = `git rev-parse HEAD`

    cap['browserstack.debug'] = true
    cap['browserstack.tunnel'] = true
    cap['acceptSslCerts'] = true
    
    Capybara::Selenium::Driver.new(app, browser: :remote, url: "https://#{username}:#{password}@hub.browserstack.com/wd/hub", desired_capabilities: cap)
  end
  
  Capybara.default_driver = :browserstack
  Capybara.app_host = 'http://localhost:3000'
  Capybara.run_server = false
else
  Capybara.register_driver :chrome do |app|
    Capybara::Selenium::Driver.new(app, browser: :chrome)
  end
  Capybara.default_driver = :chrome
end


require 'rails_helper'

if ENV.key?('BS_BROWSER')
  require 'selenium/webdriver'
  ENV['SMTP_SENDER'] = 'test@example.com'
  username = ENV.fetch('BS_USERNAME')
  password = ENV.fetch('BS_PASSWORD')

  Capybara.register_driver :browserstack do |app|
    capabilities = JSON.parse(ENV.fetch('BS_BROWSER'))

    ['device', 'browser_version'].each do |key|
      capabilities.delete(key) unless capabilities[key]
    end

    capabilities['project'] = 'PVBE'
    capabilities['build'] = `git rev-parse HEAD`

    capabilities['browserstack.debug'] = true
    capabilities['browserstack.tunnel'] = true
    capabilities['acceptSslCerts'] = true

    Capybara::Selenium::Driver.new(
      app,
      browser: :remote,
      url: "https://#{username}:#{password}@hub.browserstack.com/wd/hub",
      desired_capabilities: capabilities
    )
  end

  Capybara.default_driver = :browserstack
  Capybara.app_host = 'http://localhost:3000'
  Capybara.run_server = false
else
  require 'capybara/rspec'
  require 'capybara/poltergeist'
  Capybara.default_driver = :poltergeist
  Capybara.javascript_driver = :poltergeist
  Capybara.default_wait_time = 3
end

Use Poltergeist to run browser specs
Use Poltergeist to run browser specs

Chromedriver is slow, the browser window is annoying, and it doesn't
work properly on CircleCI since upgrading Rails.

If BS_BROWSER is defined, then we're running under Browserstack, and
should use the Selenium driver. Otherwise, we'll use Poltergeist.
