# Copyright 2006
#Mounir Errami - Modified specifically for Bibus
#m.errami@gmail.com 
# 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.
#

from __future__ import generators		# to be removed in python 2.3
try:
	import BIB
	import wx
except:
	pass
import sys
import xml.parsers.expat

DEFAULT_ENCODING = 'utf_8'

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'}
	FieldsCorrespondance={
	'Bibliographic_Type':'ref-type',
	'Address':'auth-adress',
	'Annote':None,
	'Author':'author',
	'Booktitle':'secondary-title',
	'Chapter':None,
	'Edition':'edition',
	'Editor':None,
	'HowPublished':None,
	'Institution':None,
	'Journal':'full-title',
	'Month':None,
	'Note':'notes',
	'Number':None,
	'Organizations':None,
	'Pages':'pages',
	'Publisher':'publisher',
	'School':None,
	'Series':None,
	'Title':'title',
	'Report_Type':None,
	'Volume':'volume',
	'Year':'year',
	'URL':'url',
	'Custom1':None,
	'Custom2':None,
	'Custom3':None,
	'Custom4':None,
	'Custom5':None,
	'ISBN':'isbn',
	'Abstract':'abstract'}

	Fields ={
	'author':'',
	'ref-type':'',
	'author':[],
	'year':'',
	'title':'',
	'abstract':[],
	'pages':'',
	'volume':'',
	'publisher':'',
	'edition':'',
	'url':[],
	'isbn':'',
	'notes':'',
	'secondary-title':'', 
	'auth-adress':''
	}
	
	def __init__(self, xml_file):
		self.xml_file = xml_file
		self.Parser = xml.parsers.expat.ParserCreate("utf-8")
		self.Parser.CharacterDataHandler = self.handleCharData
		self.Parser.StartElementHandler = self.handleStartElement
		self.Parser.EndElementHandler = self.handleEndElement
		self.records = []
		self.recordTemplate = importRef.Fields
		self.record= self.recordTemplate
		self.name =""
		self.dico= {}
		self.parse()
		#return self.getLibrary()
		#print "Number of references=",len(self.records)
		#self.printParsingResults()
		#self.printParsingConversion()
		
	def getLibrary(self):
		return self.convertAllRecords()
		
	def __iter__(self):
		"""Generator of records. for record in <instance>: ... """
		for article in self.convertAllRecords():
			yield article
  
	def parse(self):
		self.Parser.Parse(self.xml_file.read().encode("utf-8"),0)
		self.newRecord() # To add the last record
		
 	def printParsingResults(self):
		for record in self.records[1:3]:
			print "================New Record==================="
			for key in record.keys():
				print key,"=>",record[key]
 	def printParsingConversion(self):
		convs = self.getLibrary()
		for record in convs[1:3]:
			print "================New Record==================="
			for i in range(len(record)):
				print i,"=>",record[i]
				
	def handleCharData(self, data): 
		if self.name == 'url' or self.name == 'author' or self.name == 'abstract':
			self.record[self.name].append(unicode(data))
		elif self.name =='ref-type':
			pass # we use the name of arttribute rather than the value
		else:
			self.record[self.name]=unicode(data)
		pass
	def handleStartElement(self, name, attrs): 
		if name != 'style':
			self.name = name
		if self.name =='ref-type':
			self.record[name]=attrs['name']
			#A bit complexe. when ref-type key is found, the attrs['name'] is Journal Article 
			#The xml syntaxe is <ref-type name="Book Section">5</ref-type>. I don't want to use the numbers and use the name of ref-type
			#So that the Type variable is usable to convert
		if self.name == 'record':
			self.newRecord()
		#pass
        def handleEndElement(self, name): 
		#if self.name != 'style':
			#print 'End element:', name
		pass
	def newRecord(self):
		self.records.append(self.record)
		self.record = {'ref-type':'','author':[],'full-title':'','title':'','pages':'','volume':'','number':'','year':'','abstract':'','url':[]}
		self.record = {	'author':'','ref-type':'','author':[],'year':'','title':'','abstract':[],'pages':'','volume':'','publisher':'','edition':'','url':[],'isbn':'','notes':'','secondary-title':'','auth-adress':''}
		
	def convertAllRecords(self):
		convrecs = []
		for rec in self.records[1:]:
			crec = self.convertRecord(rec)
			convrecs.append(crec)
		self.records=convrecs
		return self.records
		
	def convertRecord(self,Record):
		"""return a list of the record fields using
		('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')"""
		Identifier = ''
		#
		try: Bibliographic_Type = BIB.BIBLIOGRAPHIC_TYPE[importRef.Type[Record['ref-type']]]
		except: Bibliographic_Type = BIB.BIBLIOGRAPHIC_TYPE['ARTICLE'] # default type = ARTICLE
		FC = importRef.FieldsCorrespondance
		# convertedRecord = [None,'',Bibliographic_Type] # also need to add biblio type
		# for key in FC.keys():
			# if key == 'Bibliographic_Type' :
				# continue
			# if FC[key]==None:
				# convertedRecord.append(' ')
			# else:
				# try:
					# convertedRecord.append(Record[FC[key]])
				# except KeyError:
					# print "Key Error here",key,FC[key]
					# pass
		# 
		# return convertedRecord
		try:Linkedfile = Record['file']
		except: Linkedfile = ''
		
		try:Address =Record['auth-address'] 
		except: Address = ''
		#
		Annote = ''	#
		#
		try: Author = ';'.join(Record['author']).replace('.','')
		except KeyError: Author = ''
		#
		try: Booktitle = Record['secondary-title']
		except KeyError: Booktitle = ''
		#
		Chapter = ''
		#
		try: Edition = Record['edition']
		except KeyError: Edition = ''
		#
		Editor = ''
		HowPublished = ''
		Institution = ''
		#
		try: Journal =  Record['full-title']
		except KeyError: Journal = ''
		#
		Month=''
		#
		Note = Record['notes']
		#
		Number =''
		#
		Organizations = ''
		#
		try: Pages = Record['pages']
		except KeyError: Pages = ''
		#
		try: Publisher = Record['Publisher']
		except KeyError: Publisher = ''
		#
		School = ''
		#
		Series = ''
		#
		try: Title = Record['title']
		except KeyError: Title = ''
		#
		Report_Type = ""
		
		#
		try: Volume = Record['volume']
		except KeyError: Volume = ''
		#
		try: Year = Record['year']
		except: Year = ''
		#
		try: URL = ''.join(Record['url'])			
		except KeyError: URL = ''
		#
		Custom1 = ''
		#
		Custom2 = ''
		#
		Custom3 = ''
		#
		Custom4 = ''
		#
		Custom5 = ''
		#
		try: ISBN = Record['isbn']
		except: ISBN = ''
		#
		try: Abstract = ''.join(Record['abstract'])
		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]
		
		

