# -*- coding: utf-8 -*-

"""Functions to make unicode handling easier for Python 2.X.
"""

import sys

def u(s, encoding='utf-8'):
	"""Convert string-like objects to unicode.
	The general idea is that, as soon as data comes into your program,
	you call u() on it to make sure it is unicode.
	@note: u() should be idempotent: i.e. u(u(x)) == u(x)
	"""
	# return unicodedata.normalize("NFKD", unicode(s)).encode('ascii', 'ignore')
	# return s.encode('raw_unicode_escape')
	# if isinstance(s, basestring):
		# if not isinstance(s, unicode):
			# try:
				# s = unicode(s, encoding)
			# except UnicodeDecodeError:
				# s = unicode(s, 'unicode_escape')
	# else:
		# s = unicode(s)
	try:
		s = unicode(s, encoding)
	except UnicodeDecodeError:
		s = unicode(s, 'unicode_escape')
	except TypeError, x:
		if 'need string' in x.args[0]:
			x = unicode(str(x), 'unicode_escape')
	return s


def test():
	print u('xx\x42\xabooo')
	print u('x\x42x\xabooo')
	print u('x\x42x\xcfooo')
	print u('x\x42x\xffooo')
	print u('boo\x40\xaboo')
	assert u('boo\x40\xaboo') == u(u('boo\x40\xaboo'))
	assert u('x\x42x\xffooo') == u(u('x\x42x\xffooo'))


	class _test(object):
		def __repr__(self):
			return 'boo\x40\xaboo'
	print u(_test())

def e(s):
	"""Encode unicode into a bytestring, for printing.
	The idea is that, just before you print anything,
	you call e() on the data to be printed."""
	if sys.getdefaultencoding() == 'ascii':
		return s.encode('utf-8')
	return s

