# frozen_string_literal: true

module CapybaraHelper

  def self.configure
    require "selenium-webdriver"
    require "capybara/rails"
    require "webdrivers" unless File.exist?("/usr/bin/chromedriver")
    require "capybara-screenshot/cucumber"

    chrome_options = {
        args: [
            "--no-sandbox",
            "--test-type",
            "--disable-infobars",
            "--window-size=1680,1050",
            "--wm-window-animations-disabled",
            "--disable-gpu",
            "--disable-dev-shm-usage",
            "--disable-setuid-sandbox",
            "--remote-debugging-port=9222",
        ],
    }

    # set for download without prompt and default directory.
    chrome_options[:prefs] = {download: {prompt_for_download: false ,
                                         default_directory: Rails.root.join("tmp/downloads").to_s }}

    Capybara.register_driver :chrome do |app|
      options = Selenium::WebDriver::Chrome::Options.new(chrome_options)
      options.headless! if ENV["CHROME_HEADLESS"]

      Capybara::Selenium::Driver.new(
          app,
          browser: :chrome,
          options: options,
          )
    end

    Capybara.javascript_driver = :chrome
    Capybara.always_include_port = true
    Capybara.server_host = ENV["LOCAL_IP"] if ENV["LOCAL_IP"]
    Capybara.reuse_server = false
    Capybara.default_max_wait_time = 30
    Capybara.server = :puma, { Silent: true }

    # Capybara::Screenshot ========================================================
    Capybara.save_path = ENV.fetch("CI_ARTIFACTS_DIR", "tmp/screenshots") # this path should match -store_artifacts path in .circleci/config.yml
    Capybara::Screenshot.autosave_on_failure = ENV["CI"].present?
    Capybara::Screenshot.register_driver(:chrome) do |driver, path|
      driver.browser.save_screenshot(path)
    end

    # create meaningful filenames
    # e.g. features/student_payments/tax.feature:9 will become features-student_payments-tax-feature-9
    Capybara::Screenshot.register_filename_prefix_formatter(:cucumber) do |scenario|
      [scenario.location.file.tr("/", "-").tr(".", "-"), scenario.location.lines.first].join("-")
    end
  end

  def self.reset_browser
    if Capybara.current_driver == Capybara.javascript_driver
      Capybara.current_session.driver.browser.manage.delete_all_cookies
    else
      Capybara.current_session.driver.browser.clear_cookies
    end
    Capybara.reset_sessions!
  end

end
