require 'rexml/child'
require 'rexml/source'

module REXML
	# This class needs:
	# * Documentation
	# * Work!  Not all types of attlists are intelligently parsed, so we just
	# spew back out what we get in.  This works, but it would be better if
	# we formatted the output ourselves.
	class AttlistDecl < Child
		include XMLTokens
		include Enumerable
		ENUMERATION = "\\(\\s*#{NMTOKEN}(?:\\s*\\|\\s*#{NMTOKEN})*\\s*\\)"
		NOTATIONTYPE = "NOTATION\\s+\\(\\s*#{NAME}(?:\\s*\\|\\s*#{NAME})*\\s*\\)"
		ENUMERATEDTYPE = "(?:(?:#{NOTATIONTYPE})|(?:#{ENUMERATION}))"
		ATTTYPE = "(CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS|#{ENUMERATEDTYPE})"
		ATTVALUE = "(?:\"((?:[^<&\"]|#{REFERENCE})*)\")|(?:'((?:[^<&']|#{REFERENCE})*)')"
		DEFAULTDECL = "(#REQUIRED|#IMPLIED|(?:(#FIXED\\s+)?#{ATTVALUE}))"
		ATTDEF = "\\s+#{NAME}\\s+#{ATTTYPE}\\s+#{DEFAULTDECL}"
		ATTLISTDECL = /^\s*<!ATTLIST\s+#{NAME}(?:#{ATTDEF})*\s*>/um

		START_RE = /^\s*<!ATTLIST/um

		attr_reader :element

		def initialize source
			super()
			md = source.match( ATTLISTDECL, true )
			raise ParseException.new( "Bad ATTLIST declaration!", source ) if md.nil?
			@element = md[1]
			@contents = md[0]

			@pairs = {}
			values = md[0].scan( ATTDEF )
			values.each do |attdef|
				unless attdef[3] == "#IMPLIED"
					attdef.compact!
					val = attdef[3]
					val = attdef[4] if val == "#FIXED "
					@pairs[attdef[0]] = val
				end
			end
		end

		def [](key)
			@pairs[key]
		end
		def include?(key)
			@pairs.keys.include? key
		end
		def each(&block)
			@pairs.each(&block)
		end

		def AttlistDecl.parse_stream source, listener
			listener.attlistdecl pull(source)
		end

		def AttlistDecl.pull source
			source.match( ATTLISTDECL, true )[1]
		end

		def write out, indent=-1
			out << @contents
		end
	end
end
