import openmedialib

#
# TODO: Refactor this
#

def change_nothing( input, post ):
	return ""

def turn_thread_on( input, post ):
	if input.get_uri( ) == "threader":
		if post:
			input.properties( ).get_property( "active" ).set( 1 )
		return "[start]"
	return ""

def turn_thread_off( input, post ):
	if input.get_uri( ) == "threader":
		if not post:
			input.properties( ).get_property( "active" ).set( 0 )
		return "[stop]"
	return ""

def dev_stdout( message ):
	print message

def dev_null( message ):
	pass

def walk( input, modifier = change_nothing, logger = dev_stdout, offset = 0 ):
	if input is not None:
		result = modifier( input, False )
		logger( ( " " * offset ) + input.get_uri( ) + result )
		i = 0
		while i < input.slots( ):
			i += walk( input.fetch_slot( i ), modifier, logger, offset + 2 )
		modifier( input, True )
	else:
		logger( ( " " * offset ) + "None" )
	return 1

def activate( input ):
	walk( input, turn_thread_on )

def deactivate( input ):
	walk( input, turn_thread_off, dev_null )

def retrieve_uri( node ):
	uri = None
	if node is not None:
		prop = node.properties( ).get_property( "rpn_uri" )
		if prop is not None and prop.valid( ):
			uri = unicode( prop.value_as_wstring( ) )
		else:
			uri = node.get_uri( )
	return uri

def dump( input, post ):
	if post:
		print retrieve_uri( input ),
		keys = input.properties( ).get_keys( )
		for i in keys:
			if str( i )[ 0:4 ] != "rpn_" and str( i ) != "debug":
				value = "<unknown>"
				property = input.properties( ).get_property( i )
				if property.is_a_int( ):
					value = property.value_as_int( )
				elif property.is_a_double( ):
					value = property.value_as_double( )
				elif property.is_a_wstring( ):
					value = property.value_as_wstring( )
				print str( i ) + "=" + str( value ),
		print
	return ""

def stack( input ):
	walk( input, dump, dev_null )

