from simpleparse.xml import xml_parser
from simpleparse.parser import Parser

class Element( object ):
	def __init__( self, element, buffer ):
		self.element = element
		self.buffer = buffer

	def __repr__( self ):
		"""Get a simple tag representation"""
		if len( self.element[0]) > 1:
			return """<%s></>"""%( self.name)
		else:
			return """<%s/>"""

	def elementChildren( self ):
		return [
			e
			for e in self.element[3][1][3]
			if e[0] == 'element'
		]

	def __list__( self ):
		"""Convert the element to a list of it's children"""
		if len( self.element[3]) > 1:
			return [
				self.__class__( e, self.buffer)
				for e in self.elementChildren()
			]
		return []
	def __len__( self ):
		"""Get the length of the element as a sequence"""
		return len(self.elementChildren())
		
	def __getslice__( self, start, stop ):
		"""Get a slice of the element children"""
		return [
			self.__class__( e, self.buffer)
			for e in self.elementChildren()[start:stop]
		]

	def __getitem__( self, index ):
		"""Get a single child as an Element"""
		e = self.elementChildren()[index]
		return self.__class__( e, self.buffer )

	def _getName( self ):
		"""Get the element name for this tag"""
		if hasattr( self, '_name'):
			return self._name
		_,start,stop,_ = self.element[3][0][3][0]
		return self.buffer[ start:stop ]
	name = property( _getName )
		

def load( filename ):
	"""Load given filename as an XML document"""
	file = open(filename).read()
	import time
	t = time.clock()
	result = Parser( xml_parser.declaration, 'document' ).parse( file )[1][1]
	deltat = time.clock()-t
	print 'parse-time', deltat, len(file)/deltat
	return Element(
		result,
		file,
	)

if __name__ == "__main__":
	import sys
	if sys.argv[1:]:
		filename = sys.argv[1]
	else:
		filename = "hamlet.xml"
	x = load( filename )
	