require 'active_support/core_ext/numeric/bytes'
require "debci/app"
require "debci/package"
require 'debci/html_helpers'
require 'debci/log'

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

    get "/?" do
      redirect "/"
    end

    before "/*" do
      next if logged_in?

      showing_log = (params[:splat].first.split("/").length == 5)
      next if showing_log

      halt 403, erb(:no_public_browsing)
    end

    # Package search
    get '/-/search' do
      @query = params[:query]
      records = Debci::Package.where("name LIKE :query", query: "%#{@query}%").order(:name)

      if records.count == 1
        redirect "/packages/#{records[0].prefix}/#{records[0].name}/"
      end

      # pagination
      results = get_page_params(records, params[:page], 10)

      erb :package_search_results, locals: { results: results }
    end

    # Package listing pages
    get "/:prefix/" do
      @package_prefixes = Debci::Package.prefixes if logged_in?
      @prefix = @moretitle = params[:prefix]
      @packages = Debci::Package.by_prefix(@prefix).order("name") if logged_in?
      erb :packagelist
    end
    get "/:prefix" do
      redirect "#{request.path}/"
    end

    # Package status pages
    get "/:prefix/:package/" do
      halt 404 unless params[:package].start_with?(params[:prefix])
      begin
        @package = Debci::Package.find_by_name!(params[:package])
        @pending_jobs = @package.jobs.pending
      rescue ActiveRecord::RecordNotFound
        halt 404
      end
      @moretitle = @package.name

      refresh!
      erb :package
    end
    get "/:prefix/:package" do
      redirect "#{request.path}/"
    end

    # Package history pages
    get "/:prefix/:package/:suite/:architecture/" do
      halt 404 unless params[:package].start_with?(params[:prefix])
      package = Debci::Package.find_by_name(params[:package])
      halt 404 unless package

      @package = package
      @suite = params[:suite]
      @architecture = params[:architecture]
      @packages_dir = 'data/packages'
      @package_dir = File.join(@suite, @architecture, package.prefix, package.name)
      @site_url = expand_url(Debci.config.url_base, @suite)
      @artifacts_url_base = expand_url(Debci.config.artifacts_url_base, @suite)
      @moretitle = "#{package.name}/#{@suite}/#{@architecture}"
      @history = package.history(@suite, @architecture).reverse_order

      # pagination
      results = get_page_params(@history, params[:page], 500)

      refresh!
      erb :history, locals: { results: results }
    end
    get "/:prefix/:package/:suite/:architecture" do
      redirect "#{request.path}/"
    end

    get "/:prefix/:package/:suite/:architecture/:run_id/" do
      halt 404 unless params[:package].start_with?(params[:prefix])
      @package = Debci::Package.find_by_name(params[:package])
      halt 404 unless @package

      begin
        @job = @package.jobs.where(
          arch: params[:architecture],
          suite: params[:suite]
        ).find(params[:run_id])
      rescue ActiveRecord::RecordNotFound
        halt 404
      end

      halt(404) if @job.files_purged?

      @too_large = @job.log_size.to_i > 500.kilobytes

      log_file = (@job.autopkgtest_dir / "log.gz").to_s
      @log = Debci::Log.new(log_file)
      @log.parse unless @too_large
      @base_url = "/data/autopkgtest/#{@job.suite}/#{@job.arch}/#{@job.package.prefix}/#{@job.package.name}/#{@job.run_id}"
      if request.env["HTTP_ACCEPT"] == "text/plain"
        redirect "#{@base_url}/log.gz"
      else
        erb :log_viewer
      end
    end

    get "/:prefix/:package/:suite/:architecture/:run_id" do
      redirect "#{request.path}/"
    end
  end
end
