# frozen_string_literal: true

# Subclasses the built cucumber junit format to add the filename and remove the cdata tag,
# where are required and incompatible respectively for CircleCI's junit parser
require "builder"
require "cucumber/formatter/backtrace_filter"
require "cucumber/formatter/io"
require "cucumber/formatter/interceptor"
require "cucumber/formatter/junit"
require "fileutils"

module TeachableCucumber
  module Formatter
    # The formatter used for <tt>--format junit</tt>
    class Junit < Cucumber::Formatter::Junit

      def build_testcase(result, scenario_designation, output)
        duration = Cucumber::Formatter::ResultBuilder.new(result).test_case_duration
        @current_feature_data[:time] += duration
        classname = @current_feature_data[:feature].name
        name = scenario_designation
        file = @current_feature_data[:feature].file
        @current_feature_data[:builder].testcase(file: file, classname: classname, name: name, time: format("%.6f", duration)) do
          if !result.passed? && result.ok?(@config.strict)
            @current_feature_data[:builder].skipped
            @current_feature_data[:skipped] += 1
          elsif !result.passed?
            status = result.to_sym
            exception = get_backtrace_object(result)
            @current_feature_data[:builder].failure(message: "#{status} #{name}", type: status) do
              @current_feature_data[:builder].text! output
              @current_feature_data[:builder].text!(format_exception(exception)) if exception
            end
            @current_feature_data[:failures] += 1
          end
        end
        @current_feature_data[:tests] += 1
      end

    end
  end
end
