# 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.
#
# OPENOFFICE_FIELDS=('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')
# Bibliographic_Type = BIB.BIBLIOGRAPHIC_TYPE[Type['PT']]
# Address = AD
# Author = FAU if present or AU
# Journal = TA
# Month = DP .split()[1]
# Number = IP
# Pages = PG
# Title = TI
# Volume = VI
# Year = DP .split()[0]
#
from __future__ import generators	# to be removed in python 2.3
import BIB

DEFAULT_ENCODING = 'latin_1'

class importRef(object):
	"""Class is iterable. Return records one by on without the id (first field).
	The id is added by the main program, usually it will be 'NULL' to get automatic field in MySQL
	but it may be diffrent for another database backend"""

 	Type={'Technical Report':'TECHREPORT'} # conversion Medline <-> Openoffice.org Publication Type: dictionary Type[Medline Name]=OpenofficeName. Only needed for NON ARTICLE

	def __init__(self,infile):
		self.infile = infile	# must be a file type. Need a readline() function.

	def __iter__(self):
		"""Generator of records. for record in <instance>: ... """
		record  = []
		line = self.infile.readline()
		while line != '':
			#print 'line = %r' %line
			if line not in  ('\n','\r\n','\r'):
				if line.startswith(' '): # it is a continuation of the previous line
					#print record,line
					record[-1] = ' '.join([record[-1],line[:-1].strip()])
				else:
					record.append(line[:-1].strip())
			elif record != []:
				yield self.__convertRecord(record)
				record  = []
			else:
				pass
			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')"""
		medlineRecord={}
		for line in record:
				medlineKey,tmpline = line.split('-',1)[0].strip(),  line.split('-',1)[1].strip()
				if tmpline.endswith('.'):
					tmpline = tmpline[:-1].rstrip()   	# remove final dot if present
				if medlineRecord.has_key(medlineKey):	   # create a new key or add to a previous one
					medlineRecord[medlineKey] = BIB.SEP.join([medlineRecord[medlineKey],tmpline])
				else:
					medlineRecord[medlineKey] = tmpline
		#print medlineRecord
		#
		Identifier = ''
		#
		try: Bibliographic_Type = BIB.BIBLIOGRAPHIC_TYPE[importRef.Type[medlineRecord['PT'].split(BIB.SEP)[0]]]
		except: Bibliographic_Type = 0	# BIB.BIBLIOGRAPHIC_TYPE['ARTICLE'] # default type = ARTICLE
		#
		try: Address = medlineRecord['AD']
		except KeyError: Address = ''
		#
		Annote = ''
		#
		try: Author = medlineRecord['FAU']  # use FAU field if it exist because it is already formatted Name, FirstName
		except KeyError:
			try:
				tmpAuthor = medlineRecord['AU'].split(BIB.SEP)
				for i in range(len(tmpAuthor)):
					tmpAuthor[i] = ', '.join(tmpAuthor[i].split(None,1))  # Replace Name FirstName with Name, FirstName
				Author = BIB.SEP.join(tmpAuthor)
			except KeyError:
				Author = ''
		#
		Booktitle = ''
		#
		Chapter = ''
		#
		Edition = ''
		#
		Editor = ''
		#
		HowPublished = ''
		#
		Institution = ''
		#
		try: Journal =  medlineRecord['TA']
		except KeyError: Journal = ''
		#
		try: Month = medlineRecord['DP'].split()[1]
		except (KeyError,IndexError): Month = ''
		#
		Note = ''
		#
		try: Number = medlineRecord['IP']
		except KeyError: Number = ''
		#
		Organizations = ''
		#
		try: Pages = medlineRecord['PG']
		except KeyError: Pages = ''
		#
		Publisher = ''
		#
		School = ''
		#
		Series = ""
		#
		try: Title = medlineRecord['TI']
		except KeyError: Title = ''
		#
		Report_Type = ''
		#
		try: Volume = medlineRecord['VI']
		except KeyError: Volume = ''
		#
		try: Year = medlineRecord['DP'].split()[0]
		except: Year = ''
		#
		#try: URL = "http://www.ncbi.nih.gov/entrez/query.fcgi?cmd=retrieve&db=pubmed&dopt=abstract&list_uids=%s"%medlineRecord['PMID']
		#try: URL = "http://view.ncbi.nlm.nih.gov/pubmed/%s"%medlineRecord['PMID']
		try: URL = "%s/%s" %(BIB.PUBMEDVIEW,medlineRecord['PMID'])
		except KeyError: URL = ''
		#
		Custom1 = ''
		#
		Custom2 = ''
		#
		Custom3 = ''
		#
		Custom4 = ''
		#
		Custom5 = ''
		#
		ISBN = ''
		#
		try: Abstract = medlineRecord['AB']
		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]
