require 'debci/app'
require 'debci/experiment'

module Debci
  module Web
    class Experiments < Debci::App
      set :views, "#{File.dirname(__FILE__)}/views"

      def paginate(data)
        get_page_params(data, params[:page], 50)
      end

      before do
        authenticate! unless request.path =~ %r{/regression-logs/$}
        refresh!
      end

      get '/' do
        @experiments = paginate(Debci::Experiment.all.includes(:owner).order('id DESC'))
        erb :experiments
      end

      get '/:id/' do
        @experiment = Debci::Experiment.find(params[:id])
        @tests = paginate(@experiment.tests.includes(control_job: [:package], test_job: []))
        @percent_completed = @experiment.percent_completed
        erb :experiment
      end

      get '/:id/regressions/' do
        @experiment = Debci::Experiment.find(params[:id])
        @tests = paginate(@experiment.tests.regressions.includes(control_job: [:package], test_job: []))
        erb :experiment_regressions
      end

      get '/:id/regression-logs/' do
        @experiment = Debci::Experiment.find(params[:id])
        @tests = @experiment.tests.regressions.includes(test_job: [:package])
        headers['Content-Type'] = 'text/plain'
        @tests.map do |test|
          "#{test.test_job.package.name}.log.gz\t#{base_url}#{log_url(test.test_job)}\n"
        end.join
      end
    end
  end
end
