# roxiadebug.py
# created: 05.06.28 jhbang
#
# ex)
# roxia_debug = True,  in config.py
# from roxiadebug import *
# roxia_trace(....)
import time, os
import config

trace_header = '[_TRACE_]'
trace_num = 0
event_header = '[_EVENT_]'
timestamp = True

g_log_file = '/tmp/' + 'mmi.log'
init_time = 0
def initDebugLog():
	global init_time
	print 'INIT DEBUG LOG: uptime'
	os.system('uptime')
	init_time = time.time()

def checkLogSize():
	import os
	global g_log_file 
	try:
		size=os.stat(g_log_file)[6]
		if size > (500*1024): # if logfile is larger than 500 K byte
			os.remove(g_log_file)
			os.system('sync')
			f = open(g_log_file, 'a+')
			f.write('*** LOGGING - RESTART ***\n')
			f.close()		
	except:
		pass
		
def debugLogC(format, *args):
	# critical mmi trace always writes to file
	# by shchun
	global g_log_file 
	try:
		if not config.netc_debug:
			return
		checkLogSize()
		logline= '%s | ' % debug_get_time() + str(format)
		for arg in args:
			logline = logline + ' ' + str(arg)

		if logline[-1] != '\n':
			logline = logline + '\n'

		print logline[:-1]

		f = open(g_log_file, 'a+')
		f.write(logline)
		f.close()
	except:
		print 'DEBUG_LOGC ERROR'
		
	return True

def debugLogN(format, *args):
	# critical mmi trace always writes to file
	# by shchun
	global g_log_file 
	try:
		if not config.netn_debug:
			return
		checkLogSize()
		logline= '%s |\t' % debug_get_time() + str(format)
		for arg in args:
			logline = logline + ' ' + str(arg)

		if logline[-1] != '\n':
			logline = logline + '\n'

		print logline[:-1]

		f = open(g_log_file, 'a+')
		f.write(logline)
		f.close()
	except:
		print 'DEBUG_LOGC ERROR'
		
	return True

def debug_get_time():
	global init_time
	return "%.3f"%(time.time()-init_time)

def roxia_get_time():
	global init_time
	return "%.3f"%(time.time()-init_time)
	
def roxia_trace(a1, *args):
	if __debug__ and config.roxia_debug:
		global timestamp
		if timestamp:
			header = trace_header + '(%s)' % roxia_get_time()
		else:
			header = trace_header
		print header, a1,
		for a in args:
			print a,
		print

def roxia_tracef(format, *args):
	if __debug__ and config.roxia_debug:
		global timestamp
		if timestamp:
			header = trace_header + '(%s)' % roxia_get_time()
		else:
			header
		print header + ' ' + format % args

def roxia_event(a1, *args):
	global trace_num
	if __debug__ and config.roxia_event:
		global timestamp
		if timestamp:
			header = event_header + '(%s)' % roxia_get_time()
		else:
			header

		trace_num += 1
		traceno = '%d,' % (trace_num)
		print header, traceno, a1,
		for a in args:
			print a,
		print
