# 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/htree-generator"

module HTree
  module WabisabiModule
    include GeneratorModule

    def generate(xml)
      return xml if xml.is_a?(String)
      return xml if xml.is_a?(Hash)
      return xml if xml.is_a?(Elem)
      if xml.is_a?(Array) && xml.length == 1 && xml[0].is_a?(Elem)
	return xml[0]
      end

      offset  = 1
      element = xml.shift.to_s

      attributes_ar = []
      while xml.first.is_a?(Hash)
	attr = xml.shift
	attributes_ar << attr
      end

      if xml.empty?
	return make(element, *attributes_ar)
      end

      ar = xml.map {|i|
	generate(i) # recursive
      }
      return make(element, *attributes_ar){ar}
    end
  end

  # make a htree from a wabisabi
  class WabisabiGenerator
    include WabisabiModule

    def to_htree(sar)
      if sar.first.is_a?(Symbol)
	generate(sar)
      else
	sar = sar.map {|a| generate(a) }
	sar
      end
    end
  end
end

if $0 == __FILE__
  require "test/unit"
  require "qwik/htree-format-xml"
  $debug = true
end

if $debug
  class TC_HTreeWabisabi < Test::Unit::TestCase
    include HTree::WabisabiModule

    def assert(e, xml)
      assert_equal(e, generate(xml).format_xml(0))
    end

    def assert_xml(e, s)
      assert_equal(e, s.format_xml)
    end

    def test_all
      assert("<a\n/>", [:a])
      assert("<a href=\"foo.html\"\n/>", [:a, {:href=>"foo.html"}])
      assert("<a\n><b\n/></a\n>", [:a, [:b]])
      assert("<html\n><body\n><p\n><a href=\"foo.html\"\n>foo</a\n></p\n></body\n></html\n>", [:html, [:body, [:p, [:a, {:href => "foo.html"}, "foo"]]]])
      @g = HTree::Generator.new
      assert("<a\n><b\n/></a\n>", [:a, @g.b])

      # test_multi_attr
      assert("<a href=\"foo.html\"\n/>", [:a, {:href=>"foo.html"}])
      assert("<a href=\"foo.html\" class=\"bar\"\n/>",
	     [:a, {:href=>"foo.html", :class=>"bar"}])
      assert("<a href=\"foo.html\" class=\"bar\"\n/>",
	     [:a, {:href=>"foo.html"}, {:class=>"bar"}])

      # test_to_htree
      g = HTree::WabisabiGenerator.new
      assert_xml("<a/>", g.to_htree([:a]))
      assert_xml("<a/>", HTree::WabisabiGenerator.new.to_htree([:a]))
    end
  end

  class TC_HTreeWabisabiObject < Test::Unit::TestCase
    include HTree::WabisabiModule

    def assert(e, xml)
      assert_equal(e, generate(xml).inspect)
    end

    def test_all
      assert("{emptyelem <a>}", [:a])
      assert("{emptyelem <a href=\"foo.html\">}", [:a, {:href=>"foo.html"}])
      assert("{elem <a> {emptyelem <b>}}", [:a, [:b]])
      assert("{elem <html> {elem <body> {elem <p> {elem <a href=\"foo.html\"> {text foo}}}}}", [:html, [:body, [:p, [:a, {:href => "foo.html"}, "foo"]]]])
    end
  end
end
