require 'pry'
require 'rspec'
require 'rspec/expectations'
require 'rspec/retry'
require 'appium_lib'
require 'appium_capybara'
require 'capybara'
require 'capybara/dsl'
require 'capybara/rspec/matchers'
require './core/configs/environment/env_config'
require './core/data/spec_data'
require './core/configs/grid_config'
require './core/configs/driver_config'
require './core/utils/JS_utils'
require './core/utils/wait_utils'
require 'rspec_junit_formatter'

include EnvConfig
include GridConfig
include JSUtils
include WaitUtils

Dir["./core/moba/pages/components/*.rb"].each { |f| require f }
Dir["./core/moba/pages/*.rb"].each { |f| require f }

unless ENV['PROPERTIES'].nil?
  require './core/utils/properties_config_utils'
  PropertiesConfigUtils.configure_environment
end

initialize_environment

RSpec.configure do |config|
  config.include Capybara::DSL
  config.include Capybara::RSpecMatchers
  config.include RSpec::Matchers

  # Rspec retry
  config.verbose_retry = true # Print retry status
  config.display_try_failure_messages = true # Print failure
  config.default_retry_count = ENV['RETRY_COUNT']

  config.tty = true # Output the color to Jenkins
  # Selenium Grid Configuration.
  # Point to Selenium Grid if needed
  Capybara.default_driver = :appium

  register_appium_driver

  $start_time = Time.now
  @driver = Capybara.current_session.driver
  saucelabs_session_id = @driver.browser.session_id
  sauce_url = build_sauce_url("#{SpecData.saucelabs_user}:#{SpecData.saucelabs_key}", saucelabs_session_id)
  puts "[INFO] Saucelabs video available on: #{sauce_url}"

  # ToDo
  # exceptions_to_hard_fail, screenshots for failure
  # Configuration around each example ran within the suite
  config.around(:each) do |example|
    example.run
    if example.exception
      puts "[INFO] '<SCENARIO :: #{example.description}>'. Failure Point in the saucelabs video: #{Time.now - $start_time}" if
      example.exception.class.to_s.include?('ExpectationNotMetError')
      grid_terminated = grid_connection_terminated?(example.exception)
      if grid_terminated
        puts "[ERROR] GRID Connection gone bad due to '#{example.exception.class}'. Re-connecting..."
        reconnect_to_grid
        sauce_url = build_sauce_url("#{SpecData.saucelabs_user}:#{SpecData.saucelabs_key}", Capybara.current_session.driver.browser.session_id)
        puts "[INFO] Saucelabs video after reconnection available on: #{sauce_url}"
        $start_time = Time.now
        example.run_with_retry
      end
    end
  end

  config.add_formatter(RSpec::Core::Formatters::DocumentationFormatter)
  if ENV['PLATFORM_NAME'] == 'iOS'
    config.add_formatter(RspecJunitFormatter, 'output/ios.xml')
  else
    config.add_formatter(RspecJunitFormatter, 'output/android.xml')
  end
  config.profile_examples = true
end
