require './core/utils/bmp_utils'
require 'capybara/dsl'

class DriverConfig

  class << self
    attr_reader :log_filepath

    include Capybara::DSL

    # @param [Symbol] level The level to save logs to
    # @param [String] File path to find the log at
    def enable_logging(level)
      timestamp = Time.now.strftime('%m_%-d_%Y_%H_%M_%S') # ex. 02_28_2017_21_09_44
      @log_filepath = "./resources/output/logs/#{timestamp}_selenium.log"
      Selenium::WebDriver.logger.level = level
      Selenium::WebDriver.logger.output = @log_filepath

      puts "[INFO] Saving Selenium Log, Level #{level.to_s}, to: #{@log_filepath}"
      return @log_filepath
    end

  end

  # Added functionality to run chrome locally.
  # If BROwSER=chrome, set driver to chrome, else default to firefox.
  def self.register_local_driver
    Capybara.register_driver :selenium do |app|
      if SpecData.browser == 'chrome'
        Capybara::Selenium::Driver.new(app, :browser => :chrome)
      else
        # Firefox
        Selenium::WebDriver::Firefox::Binary.path = firefox_path

        Capybara::Selenium::Driver.new(app,
          :browser => :firefox,
          :desired_capabilities => Selenium::WebDriver::Remote::Capabilities.firefox(marionette: false),
          :profile => create_local_profile)
      end
    end

    set_timeouts
  end

  # Creates a profile for a local Selenium WebDriver
  # Attaches a proxy to that profile if requested
  # Currently only supports Firefox
  private_class_method def self.create_local_profile
    profile = Selenium::WebDriver::Firefox::Profile.new

    if bmp_enabled?
      proxy = create_webdriver_proxy
      profile.proxy = proxy
    end

    return profile
  end

  # This method will return the path for the Firefox Binary
  # Supports returning a non-system default path to Firefox, if applicable.
  # Useful if you want Firefox 48+ for your normal usage, but want to use Firefox 45 ESR for Smoca
  # EXAMPLE: To use a non-system default path to binary, you can download Firefox.app to ~/twitch/smoca
  # Then add to ~/.bash_profile
  # export SMOCA_FIREFOX_BINARY_PATH=~/twitch/smoca/Firefox.app/Contents/MacOS/firefox-bin
  #
  # Feel free to use a different path to whichever preferred.
  # @return String The path to the Firefox binary
  def self.firefox_path
    return ENV['SMOCA_FIREFOX_PATH'] || Selenium::WebDriver::Firefox::Binary.path # Fall back to default if ENV Var doesn't exist
  end

  # Sets timeout values for the driver to use
  def self.set_timeouts
    # Investigation indicates these values should be less than the Remote Client timeout within grid_config.rb
    page.driver.browser.manage.timeouts.page_load      = 45
    page.driver.browser.manage.timeouts.script_timeout = 45
  end

end
