##

# A BigBatchedList paginates a list of items; as opposed to the
# simple BatchedList, this class only displays an environment of N pages
# to be accessed directly around the current one. 
#
# The user must render the currently displayed list and the page bar.
#
# Example:
#
#   class MyList < Borges::Component
#     def initialize(items)
#       @batcher = Borges::BigBatchedList.new(items, 5)
#     end
#  
#     def choose(item)
#       call(MyView.new(item)) # MyView is a component that views the item.
#     end
#  
#     def render_content_on(r)
#       r.list_do(@batcher.batch) do |item|
#         r.anchor(item.title do choose(item) end
#       end
#  
#       r.render(@batcher)
#     end
#   end
class Borges::BigBatchedList < Borges::BatchedList
  DEFAULT_ENV = 5

  attr_accessor :environment

  ##
  # Create a new BigBatchedList from +items+, with +size+ items per page,
  # and links +environment+ immediately surrounding pages.

  def initialize(items = [], size = DEFAULT_SIZE, environment = DEFAULT_ENV)
    super(items, size)
    @environment = environment
  end

  ##
  # Decides if the page number n is displayed, given current page and 
  # environment size.

  def should_display?(n)
    f = 1
    while f < max_pages do 
      if (n + 1) % f == 0 && (current_page - n).abs < environment * f then 
        return true
      end
      
      f *= 10
    end
    return false
  end

  ##
  # Render the page selector for the batch.

  def render_content_on(r)
    return if max_pages == 1
    
    r.div_named('batch') do
      unless on_first_page? then
        r.anchor('<<') do previous_page end
      else
        r.text('<<')
      end

      r.space

      dots = false
      0.upto(max_pages - 1) do |i|
        unless should_display?(i) then
          unless dots then
            r.space
            r.text('...')
          end
          dots = true
          next
        end
	
        dots = false
	
        r.space

        unless @current_page == i then
          r.anchor(i + 1) do @current_page = i end
        else
          r.bold(i + 1)
        end
      end

      r.space
      r.space

      unless on_last_page? then
        r.anchor('>>') do next_page end
      else
        r.text('>>')
      end
    end
  end

end



