Buildwise::App.controllers :performance do
  
  get "/:id/history", :provides => [:js] do    
    @performance_test_result = PerformanceTestResult.find_by_id(params[:id])
    return if @performance_test_result.nil?
    
    @operation_name = @performance_test_result.operation
    @build = @performance_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
    
    @test_runs = PerformanceTestResult.joins(:build).where(:operation => @operation_name).where("builds.status != ? AND builds.id <= ? AND builds.project_id = ?", "cancelled", @build.id + 3, @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
      the_duration =  (total_timings.reduce(:+) / total_timings.size).round(2)
      @recent_build_times << {time: a_build.start_time, duration: the_duration, color: (build_id == @build.id ? '#1aadce' : '#db843d')}
    end

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