# encoding: UTF-8
require 'forwardable'

module Minireq
  module Gitbook

=begin
  Tree node
  Example:
      include Md2gitbook
      r = Node.new("title")
      r << Node.new("subtitle 1")
      r << Node.new("subtitle 2")
=end
    class Node
      extend Forwardable

      attr_reader :header
      attr_reader :body
      attr_reader :items
      attr_accessor :parent

      # TODO set parent attribute
      def_delegator :@items, :<<
      def_delegator :@items, :each

      def initialize(header, body = '')
        @header = header
        @body   = body
        @parent = nil
        @items  = []
      end

      def <<(obj)
        @items << obj
        obj.parent = self if obj.is_a? Node
      end

      def level
        l = 0
        # return 0 unless @parent
        p = @parent
        while p
          l += 1
          p = p.parent
        end
        l
      end

      def visit(&block)
        return unless block_given?
        yield(self)
        each {|n| n.visit(&block)}
      end

      def find(header)
        visit{|n| return n if n.header.eql?(header)}
        return nil
      end

      def to_s
        @header
      end
    end
  end
end
