require './core/utils/stats_utils'

# This formatter interacts with Rspec and will run code depending on the status of rspec
# Such as when an example fails, when a suite finishes, etc.

# http://rubylogs.com/how-to-write-rspec-formatters-from-scratch/

$read_timeout_count = 0 # Used to track Net::ReadTimeout Exceptions. TODO: Transfer to statcounter object

module Stats
  class Formatter
    RSpec::Core::Formatters.register self, :dump_summary, :example_failed
    include StatUtils

    def initialize(output)
      # This is needed for the rspec formatter to register
    end

    def example_failed(notification)
      if notification.exception.to_s.include?('Net::ReadTimeout') # Measure the amount of Net::ReadTimeout's
        $read_timeout_count += 1
      end
    end

    def dump_summary(summary)
      if summary.failure_count == 0
        result = 'success'
      else
        result = 'failure'
      end

      # Send the stats
      gauge("#{result}.duration", (summary.duration / 60)) if ENV['PARALLEL'] != 'true' # Measures the duration and also distinguishes a success/fail result
      # TODO: Deprecate this formatter, or at least don't send the stats through it.
      gauge('warnings.net_read_timeout', $read_timeout_count) # Measures the amount of Net::ReadTimeout errors, as found in example_failed()
      puts 'Sent Stats!'
    end
  end
end
