# Copyright 2004,2005 Pierre Martineau <pmartino@users.sourceforge.net>
# This file is part of Bibus, a bibliographic database that can
# work together with OpenOffice.org to generate bibliographic indexes.
#
# Bibus is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Bibus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bibus; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
#
import time, locale
#
enMonth = [u'January', u'February', u'March', u'April', u'May', u'June', u'July', u'August', u'September', u'October', u'November', u'December']
enMonthAbb = [u'Jan', u'Feb', u'Mar', u'Apr', u'May', u'Jun', u'Jul', u'Aug', u'Sep', u'Oct', u'Nov', u'Dec']

def __fromEnglish(s):
	try:
		return unicode(enMonthAbb.index(s)+1)
	except ValueError:
		try:
			return unicode(enMonth.index(s)+1)
		except:
			return s

def format(s,uselocale=False,f=0):
	"""Return month as an unicode string with the following format
	abbreviated if f=0
	full if f=1
	number if f=2
	if uselocale = True => we use locale settings, otherwise, we return the string in English"""
	#
	encoding = locale.getlocale(locale.LC_TIME)[1]		# get current encoding for time
	s = s.strip().title()
	# we first translate the month in number representation using locale
	try: s = s.encode(encoding)
	except: pass
	try:
		ret = time.strftime('%m',time.strptime(s,'%b'))	# we first try abbreviated
	except ValueError:
		try:
			ret = time.strftime('%m',time.strptime(s,'%m'))	# or as a number ?
		except ValueError:
			try:
				ret = time.strftime('%m',time.strptime(s,'%B'))	# or as a full month ?
			except ValueError:
				ret = __fromEnglish(s)				# nothing works => try in english
	#
	if f == 0: format = '%b'
	elif f == 1: format = '%B'
	else: format = '%m'
	#
	try:
		if uselocale:	# return using locale
			ret = time.strftime(format,time.strptime(ret,'%m'))
		else:
			if f ==0:
				ret = enMonthAbb[int(ret)-1]
			elif f == 1:
				ret = enMonth[int(ret)-1]
	except:
		ret = s
	#
	try:
		ret = ret.decode(encoding)	# unicode conversion if needed
	finally:
		return ret

