class TestCaseResult < ActiveRecord::Base
  belongs_to :smoca_build
  belongs_to :test_case

  validates :result, presence: true, uniqueness: false, allow_nil: false
  validates :exception_class, uniqueness: false
  validates :exception_message, uniqueness: false
  validates :test_case_id, presence: true
  validates :screenshot_url, presence: false, length: { maximum: 255 }
  validates :backtrace, presence: false, length: { maximum: 65535 }
  validates :failing_line, presence: false, length: { maximum: 65535 }

  validates_presence_of :exception_class, if: :exception_message?

  # Checks if any of the exception detail fields are populated
  # @return [Boolean] If there's any exception data
  def has_exception_data?
    return !!(exception_class || exception_message || backtrace || failing_line || screenshot_url)
  end

  # Modifies the screenshot urls to send to an nginx proxy
  # Details: https://git-aws.internal.justin.tv/qe/smoca_screenshots
  # @return [String] URL to the screenshot
  def parsed_screenshot_url
    host_to_remove = 'https://smoca-screenshots.s3-us-west-2.amazonaws.com'
    host_to_add    = 'http://qe-smoca-screenshots.us-west2.justin.tv'
    return nil if screenshot_url.nil? # Don't gsub if the URL is nil
    return screenshot_url.gsub(host_to_remove, host_to_add)
  end

  # Converts each line of backtrace to an array
  # @return [Array] Array containing each line of the backtrace
  def backtrace_to_array
    # If nil, return empty array. Else, split the array
    return backtrace.nil? ? [] : backtrace.split(/\n/)
  end
end
