require 'rwiki/rwiki'
require 'rwiki/rddoc'

module RWiki
  class SectionProp
    def load(content)
      begin
	doc = SectionDoc.new(content.tree)
	doc.to_prop
      rescue 
	nil
      end
    end
    
    class SectionDoc < RDDoc::SectionDocument
      def summary
	return nil unless @doc && @doc.root
	text = first_child(@doc.root, RD::TextBlock)
	return nil unless text
	as_str(text.content)
      end
      
      def make_summary(str, size = 30)
	str = str.split("\n").collect {|s| s.strip}.join(" ")
	
	return nil if str.size == 0
	
	ary = str.split("")
	return str if ary.size <= size
	ary[0,size].join("") + "..."
      end

      def to_prop
	prop = {}
	s = summary
	if s
	  prop["summary"] = s
	  prop[:summary] = make_summary(s)
	end

	first_heading = nil
	ary = []
	each_section do |head, content|
	  next unless head
	  title = as_str(head.title).strip
	  first_heading = title unless first_heading
	  ary.push([head.level, title])
	end
	
	prop[:heading] = ary
	prop[:first_heading] = first_heading if first_heading
	prop
      end
    end
  end
end
  
RWiki::BookConfig.default.add_prop_loader(:section, RWiki::SectionProp.new)

