Buildwise::App.controllers :load do
  
  get "/:id/history", :provides => [:js] do    
    @load_test_result = LoadTestResult.find_by_id(params[:id])
    return if @load_test_result.nil?
    
    @operation_name = @load_test_result.operation
    @build = @load_test_result.build
    @project = @build.project


    max_test_file_history = settings.max_test_file_history
    if max_test_file_history.nil? || max_test_file_history.to_i == 0
      max_test_file_history = 10
    end
    
    project_build_ids =  Build.where(:project_id => @project.id).pluck(:id)
    current_build_index = project_build_ids.find_index(@build.id)    
    if current_build_index > max_test_file_history
      build_id_since = project_build_ids[current_build_index - max_test_file_history]
    else
      build_id_since = 0
    end    
    

    @test_runs = LoadTestResult.joins(:build).where(:operation => @operation_name).where("builds.status != ? AND builds.id <= ? AND builds.id >= ? AND builds.project_id = ?", "cancelled", @build.id + 3, build_id_since, @project.id).order("builds.id DESC").group_by(&:build_id)    
    @recent_build_times = []
    @test_runs.each do |build_id, perf_result|
      a_build = Build.find(build_id)
      total_timings =  perf_result.collect{|x| x.duration}.compact      
      avg_timing =  (total_timings.reduce(:+) / total_timings.size).round(2)
      slowest_timing =  total_timings.max
      @recent_build_times << {time: a_build.start_time, build_id: build_id, vu_count: a_build.load_vu_count, average_timing: avg_timing, slowest_timing: slowest_timing, color: (build_id == @build.id ? '#1aadce' : '#db843d')}
    end

    @recent_build_times.sort! { |a, b| a[:time] <=> b[:time] }  
    render "/load/history.js".to_sym, :layout => false            
  end
  
end