require 'smoca_common/configs/s3_config'
require './core/utils/console_prints_utils.rb'
require 'smoca_common/utils/screenshot_utils'
require './core/utils/logger_utils'

# This class is responsible for uploading failure details (Screenshots, HTML) to an S3 Bucket
#   and outputting its URL
class ScreenshotFailuresFormatter
  RSpec::Core::Formatters.register self, :example_failed
  include ConsolePrintsUtils
  include LoggerUtils

  def initialize(output)
  end

  # @param notification [RSpec::Core::Notifications::ExampleNotification] The example's notification
  def example_failed(notification)
    image_upload(notification.example)
    html_upload(notification.example)
  end

  # @param example [RSpec::Core::Example] The test example
  private def image_upload(example)
    filepath = ScreenshotUtils.locate_failure_screenshot(example)
    return nil if filepath.nil?
    s3_url = S3Config.upload_file(filepath)
    example.metadata[:screenshot][:url] = s3_url
    display_url(s3_url, 'Screenshot')
  end

  # @param example [RSpec::Core::Example] The test example
  private def html_upload(example)
    filepath = ScreenshotUtils.locate_failure_html(example)
    return nil if filepath.nil?
    s3_url = S3Config.upload_file(filepath)
    example.metadata[:screenshot][:html_url] = s3_url
    display_url(s3_url, 'HTML')
  end

  # Prints an error message of the converted S3 URL
  # @param s3_url [String] The original S3 URL to convert
  # @param type [String] The type of attachment to display to the user, i.e., Screenshot or HTML.
  private def display_url(s3_url, type)
    url = ScreenshotUtils.convert_s3_url(s3_url)

    if url.nil? # If the URL was not able to be converted
      logger.error("Unable to convert screenshot url. Original: #{s3_url}")
      return nil
    end

    string = "\t#{type}: #{url}"
    error_message(string)
  end
end
