require "cucumber/formatter/stepdefs"

module Support
  module Formatters
    class Unused < Cucumber::Formatter::Stepdefs
      def print_summary
        add_unused_stepdefs
        keys = @stepdef_to_match.keys.sort_by(&:regexp_source)
        puts "The following steps are unused...\n---------"
        @unused_steps = 0
        iterate_keys(keys)
      end

      def iterate_keys(keys)
        keys.each do |stepdef_key|
          next unless @stepdef_to_match[stepdef_key].none?
          location = stepdef_key.location.to_s
          next if location =~ %r{/debug_steps.rb:\d+$}
          puts "#{stepdef_key.regexp_source}\n#{location}\n—"
          @unused_steps += 1
          puts "unused steps: #{@unused_steps}"
        end
        puts "unused steps: #{@unused_steps}"
        return fail(
          Exception,
          "There are unused step definitions, please clean them up!"
        ) if @unused_steps > 0
      end
    end
  end
end
