require "debci/app"
require 'debci/html_helpers'
require 'debci/graph'

module Debci
  class Status < Debci::App
    include Debci::HTMLHelpers
    set :views, "#{File.dirname(__FILE__)}/html/templates"

    configure do
      set :suites, Debci.config.suite_list
      set :archs, Debci.config.arch_list
    end

    def filter_and_paginate(jobs)
      query = params.filter { |k| [:arch, :suite].include?(k.to_sym) }
      get_page_params(jobs.where(query), params[:page], 200)
    end

    before do
      redirect "#{request.path}/" if request.path !~ %r{/$}
    end

    get "/" do
      erb :status
    end

    get "/alerts/" do
      @tmpfail = filter_and_paginate(Debci::Job.tmpfail)
      @alert_number = Debci::Job.tmpfail.length

      erb :status_alerts
    end

    get "/failing/" do
      @jobs = filter_and_paginate(Debci::Job.fail)
      @failing_number = Debci::Job.fail.length
      @packages_per_page = Debci.config.failing_packages_per_page

      erb :status_failing
    end

    get "/pending/" do
      @pending = filter_and_paginate(Debci::Job.pending)
      @status_per_page = Debci.config.pending_status_per_page.to_i
      @suites_jobs = Hash[
        Debci.config.suite_list.map do |x|
          [x, Debci::Job.pending.where(suite: x).count]
        end
      ]

      erb :status_pending_jobs
    end

    get "/pending/:suite/" do
      suite = params[:suite]
      @pending = Debci::Job.pending.where(suite: suite)
      @pending_jobs = Debci::Job.pending.count
      @status_per_page = Debci.config.pending_status_per_page.to_i
      @suites_jobs = Hash[
        Debci.config.suite_list.map do |x|
          [x, Debci::Job.pending.where(suite: x).count]
        end
      ]

      erb :status_pending_jobs, locals: { results: @pending }
    end

    get "/reject_list/" do
      @reject_list = Debci.reject_list
      erb :reject_list
    end

    get "/platform-specific-issues/" do
      @issues = Debci::Job.platform_specific_issues
      erb :platform_specific_issues
    end

    get "/slow/" do
      @slow = filter_and_paginate(Debci::Job.slow.includes(:package).order("packages.name"))
      erb :status_slow
    end
  end
end