# PDF-O-Matic is copyright (c) 2009, Brett Neumeier.
#
# PDF-O-Matic may be used under the terms of the GPL.  See
# COPYING.GPL, provided in this distribution, for full details.
#
# DOJ and CompNet Design, Inc., are granted a perpetual license to
# use, extend, modify, and redistribute the PDF-O-Matic software as
# they wish, without restriction.

require 'pdf_helpers'

class ItemBox

  class ItemBoxItem
    include PdfHelpers
    def initialize(pdf, item)
      @pdf = pdf
      @item = item
      @text = ''
    end
    attr_reader :pdf, :text

    def height(width_of_textfield)
      height_of_text(text, width_of_textfield)
    end

    def [](key)
      @item[key]
    end

    def list_element
      @item['prefix']
    end
  end

  class SeparatorItem
    def text
      ' '
    end
    def height(width_of_textfield)
      1
    end
    def method_missing(*args)
      ''
    end
    def [](key)
      nil
    end
  end

  class ContinuedItem < ItemBoxItem
    def name
      if @item.respond_to?(:name) && @item.name.size > 0
        @item.name
      else
        @item.text
      end
    end

    def text
      "(continued)"
    end

    def method_missing(*args)
      ''
    end
  end

  def initialize(pdf)
    @pdf = pdf
    @items = []
  end
  attr_reader :pdf, :items

  def add_all(character)
    raise "Override me in a subclass to do the right thing"
  end

  # Pull items off the front of the list until we run out, or
  # have enough to fill up the specified region.
  def pull_items_for_region(height_in_rows, width_of_textfield)
    rows_used = 0
    collector = []
    while items.size > 0
      break if (rows_used + height_of(0, width_of_textfield) > height_in_rows)
      rows_used += height_of(0, width_of_textfield)
      collector << items.delete_at(0)
      if collector.last['list']
        current_list = collector.last
      elsif current_list && !collector.last.list_element
        current_list = nil
      end
    end
    items.delete_at(0) if SeparatorItem === items[0]
    # We have run out of room.  If we're currently in a list,
    # push a "continued" item onto the front of the collection.
    if items.size > 0 && items[0].list_element && current_list
      cont = ContinuedItem.new(pdf, current_list)
      items.insert(0, cont)
    end
    collector
  end

  def height_of(item_index, width_of_textfield)
    items[item_index].height(width_of_textfield)
  end

  def total_height(width_of_textfield)
    items.inject(0) { |sum, item| sum += item.height(width_of_textfield) }
  end

end
