# 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.
#
# EndNote refer format
# from http://www.ecst.csuchico.edu/~jacobsd/bib/formats/endnote.html
#
import BIB
import Format.Converter
from bibOOo.CONST import bibOOo_italic, bibOOo_bold, bibOOo_underline, bibOOo_caps, bibOOo_smallcaps

DEFAULT_ENCODING = 'utf-8'

class exportRef(object):
	"""Class is iterable. Return records one by one."""
	def __init__(self,infile,bibStyle):
		self.infile = infile	# must be a file type. Need a write() function.
		self.bibStyle = bibStyle	# this is the dict containing the style
		self.conv = self.__getConverter(self.bibStyle)	# converter to format fields

	def __getConverter(self,style):
		"""Set the Converter or read from default
		Take into account the different versions of bibus styles"""
		if style:
			if style['version'] == 1.0:
				return Format.Converter.Converter(conv=style)
			else:
				return Format.Converter.Converter(conv=style['fields'])
		else:
			return Format.Converter.Converter()

	def write(self,ref):
		"""write(ref)"""
		record = self.__convertRecord(ref)
		if record:
			self.infile.write(record)
			self.infile.write('\n')
			
	def __convertRecord(self,ref):
		"""Convert a OOo reference to an= html record
		input ==
		('Id','Identifier', 'Bibliographic_Type', 'Address', 'Annote', 'Author', 'Booktitle', 'Chapter', 'Edition', 'Editor','HowPublished', 'Institution', 'Journal', 'Month', 'Note', 'Number', 'Organizations', 'Pages', 'Publisher', 'School', 'Series', 'Title', 'Report_Type', 'Volume', 'Year', 'URL', 'Custom1', 'Custom2', 'Custom3', 'Custom4', 'Custom5', 'ISBN','Abstract')"""
		#
		formattedRef = []
		for field in BIB.BIB_FIELDS[1:-1]:
			try:
				func,param = self.conv[BIB.BIB_TYPE[ref[2]]][field]
				tmpdata =  apply(func,(ref[ BIB.BIBLIOGRAPHIC_FIELDS[field] ],self.conv['locale']) + param)
				formattedRef.append( tmpdata )
			except:
				# because of an error, we did not format the field
				formattedRef.append( ref[ BIB.BIBLIOGRAPHIC_FIELDS[field] ] )
		#
		record = self.format(formattedRef)
		return record

	def __htmlStyle(self,charstyle):
		"""
		return a function that format an unicode string in HTML
		corresponding to charStyle
		return a tuple
		the HTML tag before
		e.g. <b><i>
		the html tag after
		e.g. </b></i>
		"""
		before,after = BIB.HTML_FONT_SIZE
		# calculating style name
		italic,bold,underline,caps = '','','',''
		if charstyle & bibOOo_italic: before,after = '<i>' + before,'</i>' + after
		if charstyle & bibOOo_bold: before,after = '<b>' + before,'</b>' + after
		if charstyle & bibOOo_underline: before,after = '<u>' + before,'</u>' + after
		if charstyle & bibOOo_caps or charstyle & bibOOo_smallcaps:
			return lambda x: before + x.upper() + after
		else:
			return lambda x: before + x + after
		#return lambda x: before + f(x) + after
		
	def format(self,ref):
		"""Format the reference ref according to current bibus style"""
		tmp=[]
		for (tokentype,token,style) in self.bibStyle['ordering'][BIB.BIB_TYPE[ref[1]]]:
			if tokentype == 'text':
				tmp.append( self.__htmlStyle(style)(token) )
			elif tokentype == 'field':
				tmp.append( self.__htmlStyle(style)(ref[BIB.BIBLIOGRAPHIC_FIELDS[token]-1]) )
			elif tokentype == 'tab':
				if style == u' ': style = '&nbsp; '
				tmp.append( style*int(token/500) )
		tmp.append('<p>')
		return ''.join(tmp)
		
