# util.py
#
# Misc static helpers.
#
# martind 2008-11-22, 16:12:53
#

import datetime
import hashlib
import re
import time

__all__ = [
	'transcode', 'to_datetime', 'from_datetime', 'now',
	'generate_entry_uid'
]


def transcode(str):
	"""
	Preprocessing for every single text string we store. Returns valid Unicode (NOT UTF-8).
	"""
	if str==None:
		return None
	return unicode(str)

strip_html_pattern = re.compile(r'\s*<.+?>\s*')

def strip_html(str):
	"""
	Strips all HTML tags. Atm this is just a stupid regex, which will break in all kinds
	of corner cases; but it's simple enough for a first version.
	"""
	if str==None:
		return None
	return strip_html_pattern.sub(' ', str)

def excerpt(str, maxlen):
	"""
	Truncates after a max length, appends an ellipsis ("...").
	"""
	if str==None:
		return None
	if (len(str)<=maxlen):
		return str
	return str[:maxlen-3] + u'...'

def to_datetime(_9tuple):
	"""
	Takes a GMT 9-tuple as generated by feedparser, converts it into a
	timestamp (a floating point number as generated by time.mktime.)
	"""
	if _9tuple==None:
		return None
	return time.mktime(_9tuple)

def from_datetime(datetime):
	"""
	Takes a UTC timestamp (a datetime object)
	and converts it into a 9-tuple to be used by feedparser.
	"""
	if datetime==None:
		return None
	return datetime.utctimetuple()

def now():
	"""
	Creates a UTC timestamp (as datetime instance.)
	"""
	return datetime.datetime.utcnow()

def generate_entry_uid(*fields):
	"""
	TODO: stopgap measure. need to audit this.
	"""
	m = hashlib.sha1()
	for field in fields:
		if field!=None:
			m.update(field.encode('utf-8'))
	return u'generated:' + m.hexdigest()
