# 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
#
from __future__ import generators		# to be removed in python 2.3
import BIB

DEFAULT_ENCODING = 'cp1252'

class importRef(object):
	"""Class is iterable. Return records one by one with None for the id (first field)."""
	# conversion EndNote <-> Openoffice.org Publication Type: dictionary Type[Medline Name]=OpenofficeName. Only needed for NON ARTICLE
 	Type={
	'Artwork':'MISC',
	'Audiovisual Material':'MISC' ,
	'Book':'BOOK' ,
	'Book Section':'INBOOK' ,
	'Computer Program':'MISC' ,
	'Conference Proceedings':'INPROCEEDINGS' ,
	'Edited Book':'BOOK' ,
	'Generic':'MISC' ,
	'Journal Article':'ARTICLE' ,
	'Magazine Article':'MISC' ,
	'Map':'MISC' ,
	'Newspaper Article':'MISC' ,
	'Patent':'MISC' ,
	'Personal Communication':'UNPUBLISHED' ,
	'Report':'TECHREPORT' ,
	'Thesis':'PHDTHESIS'}

	def __init__(self,infile):
		self.infile = infile	# must be a file type. Need a readline() function.
		while self.infile.read(1) != '%': pass	# this is needed because EndNote8 refer files start with strange chars
		else: self.infile.seek(-1,1)

	def __iter__(self):
		"""Generator of records. for record in <instance>: ... """
		record  = []
		line = self.infile.readline()
		reserved = ''
		while line != '':
			#print 'line = %r' %line
			if line not in  ('\n','\r\n','\r'):
				if not line.startswith('%'): # it is a continuation of the previous line
					record[-1] = ' '.join( (record[-1],reserved + line[:-1].strip()) )
				elif line.startswith('%0'):
					if record != []:
						yield self.__convertRecord(record)
						record  = []
					record.append(line[:-1].strip())
				else:
					record.append(line[:-1].strip())
				reserved = ''
			else:
				reserved = reserved + line	# we keep empty lines for latter
			line = self.infile.readline()
		else:
			if record != []: yield self.__convertRecord(record)

	def __convertRecord(self,record):
		"""return a list of the record fields using
		('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')"""
		Record={}
		for line in record:
				refKey,tmpline = line[:2].strip(),line[2:].strip()
				if tmpline.endswith('.'):
					tmpline = tmpline[:-1].rstrip()   	# remove final dot if present
				if Record.has_key(refKey):	   # create a new key or add to a previous one
					Record[refKey] = BIB.SEP.join([Record[refKey],tmpline])
				else:
					Record[refKey] = tmpline
		#print Record
		#
		Identifier = ''
		#
		try: Bibliographic_Type = BIB.BIBLIOGRAPHIC_TYPE[importRef.Type[Record['%0'].split(BIB.SEP)[0]]]
		except: Bibliographic_Type = BIB.BIBLIOGRAPHIC_TYPE['ARTICLE'] # default type = ARTICLE
		#
		Address = ''
		#
		Annote = ''	# EndNote use the %U for URL instead of Annotation
		#
		try:
			Author = Record['%A'].replace('.','')	# remove all the dots
			if Author.find(",") == -1:			  # either FirstName Middle Name or Name, First Middle
				authors = Author.split(BIB.SEP)
				for i in xrange(len(authors)):
					auth = authors[i]
					#print auth
					try:
						authors[i] = "%s, %s"%(auth.rsplit(None,1)[1].strip(),auth.rsplit(None,1)[0].strip())
					except IndexError:
						pass
				Author = BIB.SEP.join(authors)
		except KeyError: Author = ''
		#
		try:
			Booktitle = Record['%B']
		except KeyError: Booktitle = ''
		#
		Chapter = ''
		#
		try: Edition = Record['%7']
		except KeyError: Edition = ''
		#
		try: Editor = Record['%E'].replace('.','')	# remove all the dots
		except KeyError:
			try: Editor = Record['%Y'].replace('.','')	# series editor
			except KeyError: Editor = ''
		#
		try: HowPublished = Record['%9']
		except KeyError: HowPublished = ''
		#
		try: Institution = Record['%Q']
		except KeyError: Institution = ''
		#
		try: Journal =  Record['%J']
		except KeyError: Journal = ''
		#
		try: Month = Record['%D'].split()[1]
		except: Month = ''
		#
		Note = ''
		#
		try: Number = Record['%N']
		except KeyError: Number = ''
		#
		try: Organizations = Record['%Q']
		except KeyError: Organizations = ''
		#
		try: Pages = Record['%P']
		except KeyError: Pages = ''
		#
		try: publiAddress = Record['%C']
		except KeyError: publiAddress = ''
		if publiAddress:
			try: Publisher = ', '.join( (Record['%I'], publiAddress) )	# Publisher, Address
			except KeyError: Publisher = publiAddress
		else:
			try: Publisher = Record['%I']
			except KeyError: Publisher = ''
		#
		School = ''
		#
		try: Series = Record['%S']
		except KeyError: Series = ''
		#
		try:
			Title = Record['%T']
		except KeyError:
			Title = ''
		#
		try: Report_Type = Record['%9']
		except KeyError: Report_Type = ''
		#
		try: Volume = Record['%V']
		except KeyError: Volume = ''
		#
		try: Year = Record['%D'].split()[0]
		except: Year = ''
		#
		try: URL = Record['%U']			# EndNote put the URL in %U
		except KeyError: URL = ''
		#
		try: Custom1 = Record['%K']			# we put keywords in Custom1
		except KeyError: Custom1 = ''
		#
		try: Custom2 = Record['%F']			# we put Caption in Custom2
		except KeyError: Custom2 = ''
		#
		Custom3 = ''
		#
		Custom4 = ''
		#
		Custom5 = ''
		#
		ISBN = ''
		#
		try: Abstract = Record['%X']
		except KeyError: Abstract = ''
		#
		#print [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]
		return [None,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]
