# $Id: qtree.rb,v 1.3 2004/05/11 13:08:23 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require "htree"

module HTree
  module Node
    def r(i=-1)
      to_rexml.to_s(i)
    end
  end

  class Generator
    def method_missing(symbol, *args, &block)
      Generator.make(symbol, *args, &block)
    end

    def make(symbol, *args, &block)
      Generator.make(symbol, *args, &block)
    end

    def self.make(symbol, *args, &block)
#      qp symbol, args, block
      ar = []
      ar << symbol.to_s

      if 0 < args.length
	attr = {}
	args[0].each {|k, v|
	  attr[k.to_s] = v.to_s
	}
	ar << attr
      end

      if block
	y = block.call
	ar << y
      end

      Elem.new(*ar)
    end

  end

  class Template
    def initialize(str)
      @str = parse_str(str)
    end

    def apply(sdata=nil)
      data = {}
      data = symbol_to_str(sdata) if sdata
      #qp data, @str, data['t']
      result = HTree{@str}
      result
    end

    private

    def symbol_to_str(sdata)
      data = {}
      sdata.each {|k, v|
	data[k.to_s] = v.to_s
      }
      data
    end

    def parse_str(str)
      str.gsub(/id='([_a-z]+)'/){|r|
	"_text=\"data['#{$1}']\""
      }
    end

    def nu_remove_spaces(str)
      str2 = ""
      str.each_line {|line|
	str2 << line.sub(/^\s+/, '')
      }
      str = str2.gsub(/\n/, '')
      str
    end

  end
end
