require 'spec_helper'
require 'debci/app'

describe Debci::App do
  class App < Debci::App
    set :raise_errors, true
    set :show_exceptions, false

    def erb(template, *args, **opts)
      self.class.last_template = template unless template.to_s =~ /^_/
      super
    end

    class << self
      attr_accessor :last_template
    end
  end

  def app
    Rack::Builder.new do
      run App
    end
  end

  include Rack::Test::Methods

  let(:theuser) { Debci::User.create!(username: 'debci') }

  def last_template
    App.last_template
  end

  it 'renders Not Found template on 404' do
    get '/bla'
    expect(last_template).to eq(:not_found)
  end

  it 'renders log expired template' do
    package = Debci::Package.create!(name: 'xpkg')
    job = package.jobs.create!(
      date: Time.now - 2.years,
      suite: 'unstable',
      arch: 'arm64',
      requestor: theuser,
    )
    get "/data/autopkgtest/unstable/arm64/x/xpkg/#{job.run_id}/log.gz"
    expect(last_template).to eq(:log_expired)
  end

  it 'renders normal 404 for unexisting jobs' do
    Debci::Package.create!(name: 'xpkg')
    get "/data/autopkgtest/unstable/arm64/x/xpkg/1237289371289/log.gz"
    expect(last_template).to eq(:not_found)
  end

  context 'pagination' do
    it 'links to the last page' do
      pages = Debci::App.get_page_range(1, 30)
      expect(pages).to eq([1, 2, 3, 4, 5, 6, nil, 30])
    end
    it 'links to the first page' do
      pages = Debci::App.get_page_range(30, 30)
      expect(pages).to eq([1, nil, 25, 26, 27, 28, 29, 30])
    end

    it 'links to first and last page' do
      pages = Debci::App.get_page_range(15, 30)
      expect(pages).to eq([1, nil, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, nil, 30])
    end
    it 'links to all pages when there are few of them' do
      pages = Debci::App.get_page_range(1, 5)
      expect(pages).to eq([1, 2, 3, 4, 5])
    end
    it 'links to all pages when on page 6 of 11' do
      pages = Debci::App.get_page_range(6, 11)
      expect(pages).to eq([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
    end
  end
end
