import os, urllib
import wx

''' 
A Insertion plugin for WikidPad to show the members of WikidPad objects 

Written by Eric Tolman (tolmaneric@gmail.com)
'''
WIKIDPAD_PLUGIN = (("InsertionByKey", 1),)

def describeInsertionKeys(ver, app):
	"""
	Adds a list member insertion.  The listmember can specific a specific variable to list, and a recursion depth.
	If no variables are given, it uses a set of defaults.
	If no depth is given, it recurses just once.
	
	Examples
	[:listmembers:]			Would output the default set (wiki, editor, exporter, exporttype, insToken
	[:listmembers:wiki;2] 	Would output the members of wiki and the members of each of wiki's data members
	[:listmembers:wiki.BackgroundColour]	Would output the members of wiki.BackgroundColour
	
	"""
	return ((u"listmembers", ("wikidpad_language",), ListMembersHandler),)


class ListMembersHandler:
	"""
	Class fulfilling the "insertion by key" protocol.
	"""
	def __init__(self, app):
		self.app = app

	def taskStart(self, exporter, exportType):
		pass

	def taskEnd(self):
		pass
		
	def outputSubVariables(self, depth, maxDepth, parent, variables, wiki, editor, exporter, exportType, insToken):
		result = u""
		tabstring = "\t" * depth
		for var in variables:
			if not ((var.startswith("__") and var.endswith("__")) or (var == "im_class") or (var == "im_func") or (var == "im_self")):
				wholeVar = var
				if depth == 0:
					result += "\n++"+var+": "
					doc = eval(var).__doc__
					if doc != None:
						result += str(doc)
					result += "\n"
				else:
					result += tabstring;
					result += "*<<" + var + ">>*\n"
					wholeVar = parent + "." + var
				if depth < maxDepth:
					result += self.outputSubVariables(depth + 1, maxDepth, wholeVar, dir(eval(wholeVar)), wiki, editor, exporter, exportType, insToken)
		return result
	

	def createContent(self, exporter, exportType, insToken):
		"""
		Iterates the expression given, or a set of defaults, and outputs members.
		"""

		variables = ['wiki', 'editor', 'exporter', 'exportType', 'insToken']
		if insToken.value != None and len(insToken.value) > 0:
			variables = [ insToken.value ]
		result = u""
		
		maxDepth = 1;
		if len(insToken.appendices) > 0:
			maxDepth = int(insToken.appendices[0]);
		
		wiki = exporter.mainControl
		editor = wiki.getActiveEditor()
		result += self.outputSubVariables(0, maxDepth, "", variables, wiki, editor, exporter, exportType, insToken)
		return result

	def getExtraFeatures(self):
		return ()