# frozen_string_literal: true

require 'indicina/constants'
require 'indicina/patches'
require 'indicina/persistence'
require 'indicina/rendering'


class RunsIndex

  attr_reader :runs

  def initialize(location, url)
    @runs = Indicina.runs.by_target(location, url)
  end

  def run
    return @run if instance_variable_defined?(:@run)

    median_run_load_times.sort_by { |lt| (lt - median_load_time).abs }.each do |lt|
      run = runs.where(load_time: lt, is_median: true).first
      test = Indicina.tests.by_pk(run.test_id)
      return @run ||= run if test&.has_video
    end
  end

  def test
    @test ||= Indicina.tests.by_pk(run.test_id)
  end

  def data_points
    @data_points ||= runs.count
  end

  def load_times
    @load_times ||= runs.select(:load_time).to_a.map { |dp| dp['load_time'] }.sort
  end

  def median_points
    @median_points ||= runs.where(is_median: true).count
  end

  def median_run_load_times
    @median_run_load_times ||= runs.select(:load_time).where(is_median: true).to_a.map { |dp| dp['load_time'] }.sort
  end

  def median_load_time
    half_count = load_times.count / 2
    @median_load_time ||= load_times.count.odd? ? load_times[half_count + 1] : (load_times[half_count] + load_times[half_count + 1]) / 2
  end
end