require 'json'

class SmocaBuild < ActiveRecord::Base
  has_many :test_case_results, dependent: :destroy
  include Filterable

  validates :initiated_at, presence: true, allow_nil: false
  validates :id, uniqueness: true, allow_nil: false
  validates :developer, presence: true, uniqueness: false
  validates :job_name, presence: true

  # There shouldn't be 2 same build_id's of the same job
  validates_uniqueness_of :build_id, :scope => :job_name, :allow_nil => true, :allow_blank => true

  scope :developer, -> (developer) { where developer: developer }
  scope :result,    -> (result)    { where result: result }
  scope :date,      -> (start_date, end_date) { where initiated_at: start_date..end_date}

  def name
    if build_id
      return "#{job_name} \##{build_id}"
    else
      return "#{job_name} (unknown id)"
    end
  end

  # Helper to display the result on pages.
  # Factors in pending status when a result is unassigned
  # @return [String] The build result to display on a page
  def display_result
    if pending?
      return 'pending'
    elsif !result.blank?
      return result
    else
      return 'unknown'
    end
  end

  def passed_test_cases
    return test_case_results.where(result: 'passed')
  end

  def failed_test_cases
    return test_case_results.where(result: 'failed')
  end

  def skipped_test_cases
    return test_case_results.where(result: 'pending')
  end

  # @return [String] if a Jenkins Log URL is available
  # @return [NilClass] if no Jenkins Log URL is available
  def jenkins_log_url
    return nil if build_id.blank? || job_name.blank?
    return "https://jenkins.internal.justin.tv/job/#{job_name}/#{build_id}/console"
  end
end
