# Copyright (C) 2003-2005 Kouichirou Eto, All rights reserved.

$LOAD_PATH.unshift("../../compat") unless $LOAD_PATH.include?("../../compat")
require "htree"
$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "qwik/qp"

module HTree
  module Node
    def to_wabisabi # make a wabisabi from a htree
      ar = []
      ar << name_to_wabisabi.intern
      if 0 < attributes.length
	ar << attr_to_wabisabi(attributes)
      end
      children.each {|h|
	case h
	when Elem, Text, Comment
	  ar << h.to_wabisabi
	else
	  qp "what?", h
	end
      }
      ar
    end

    def name_to_wabisabi
     name.sub("{http://www.w3.org/1999/xhtml}", "")
    end

    def attr_to_wabisabi(attr)
      h = {}
      attr.each {|k, v|
	h[k.to_s.intern] = v.to_s
      }
      h
    end
  end

  class Comment
    def to_wabisabi
      [:"!--", @content]
    end
  end

  class Text
    def to_wabisabi
      to_s
    end
  end

  class Doc
    def to_wabisabi
      children.map {|child|
	child.to_wabisabi
      }
    end
  end

  class DocType
    def to_wabisabi
      [:"!DOCTYPE", root_element_name, "PUBLIC",
	public_identifier, system_identifier]
    end
  end
end

if $0 == __FILE__
  require "test/unit"
  require "qwik/qp"
  $debug = true
end

if $debug
  class TC_HTree_to_wabisabi < Test::Unit::TestCase
    def assert(e, htree)
      assert_equal(e, htree.to_wabisabi)
    end

    def test_all
      # test_name_to_wabisabi
      e = HTree::Elem.new("a")
      assert_equal("a", e.name_to_wabisabi)

      # test_htree_elem_to_wabisabi
      assert([:a], e)
      e = HTree::Elem.new("b", e)
      assert([:b, [:a]], e)
      e = HTree::Elem.new("a", {"href"=>"foo.html"})
      assert([:a, {:href=>"foo.html"}], e)

      # test_htree_text_to_wabisabi
      e = HTree::Text.new("a")
      assert("a", e)

      # test_htree_comment_to_wabisabi
      e = HTree::Comment.new("a")
      assert_equal("a", e.content)
      assert([:"!--", "a"], e)
      doc = HTree("<!--c-->")
      assert([[:"!--", "c"]], doc)

      # test_htree_doc_to_wabisabi
      e = HTree::Elem.new("a")
      doc = HTree::Doc.new(e)
      assert_equal("#<HTree::Doc {emptyelem <a>}>", doc.inspect)
      assert([[:a]], doc)

      # test_real_situation
      str = <<"EOT"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD html 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><title>t</title></head><body><p>b</p></body></html>
EOT
      doc = HTree(str)
      assert([[:"!DOCTYPE", "html", "PUBLIC",
		 "-//W3C//DTD html 4.01 Transitional//EN",
		 "http://www.w3.org/TR/html4/loose.dtd"], "\n",
	       [:html, [:head, [:title, "t"]], [:body, [:p, "b"]]], "\n"], doc)
    end
  end
end
