# 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 BIB
import wx

# setting some values for bibus. Copied from BIBbase to bibOOo.CONST
# this is to propagate modifications made by the user in BIBbase to bibOOo.CONST
import bibOOo.CONST
bibOOo.CONST.SEP = BIB.SEP
bibOOo.CONST.bibOOo_cit_baseCharStyleName = BIB.bibOOo_cit_baseCharStyleName		# base style for citations
bibOOo.CONST.bibOOo_index_baseCharStyleName = BIB.bibOOo_index_baseCharStyleName	# base style for bibliography index
bibOOo.CONST.BIB_TYPE = BIB.BIB_TYPE
bibOOo.CONST.BIBLIOGRAPHIC_TYPE = BIB.BIBLIOGRAPHIC_TYPE
bibOOo.CONST.BIB_FIELDS = BIB.BIB_FIELDS[1:-1]
bibOOo.CONST.BIBLIOGRAPHIC_FIELDS = {}
for i in range(len(bibOOo.CONST.BIB_FIELDS)):
	bibOOo.CONST.BIBLIOGRAPHIC_FIELDS[bibOOo.CONST.BIB_FIELDS[i]] = i
#
# strings to be translated in your program
# by overwriting them
# in bibOOoBase
bibOOo.CONST.msg1 = _("Making a copy of the current document ...")
bibOOo.CONST.msg2 = _("Creating styles ...")
bibOOo.CONST.msg3 = _("Updating references ...")
bibOOo.CONST.msg4 = _("Updating index ...")
bibOOo.CONST.msg5 = _("Deleting old index and citations ...")
bibOOo.CONST.msg6 = _("Done")
bibOOo.CONST.msg7 = _("Inserting citations in text")
# in bibOOoPlus
bibOOo.CONST.msg8 = _("Formating citations ...")
bibOOo.CONST.msg9 = _("Looking for duplicates ...")
bibOOo.CONST.msg10 = _("Solving duplicates ... (%s series of duplicates)")
bibOOo.CONST.msg11 = _("Fusing citations ...")
bibOOo.CONST.msg12 = _("Inserting citations in text (%s ranges)")
#


from bibOOo.bibOOoPlus import *

class bibusOOo(bibOOoPlus):
	def __init__(self,db):
		self.db = db
		bibOOoPlus.__init__(self,BIB.FORMAT_DICO,BIB.OO_CON_TYPE,BIB.OO_HOST,BIB.OO_PORT,BIB.OO_PIPE,\
		lambda identifier: db.getRefFromIdentifier(identifier,collist=BIB.BIB_FIELDS[1:-1])[0] )

	def storeUnknownRef(self):
		"""Store in the database the unknown references found in the document
		return a list of the stored Identifiers
		The identifiers may be changed in order to be unique in the db
		and they are updated accordingly in the current doc"""
		#
		newKeys = []		# list of the captured identifiers for return
		old2New = {}		# dictionary that give for old Identifier the New Identifier used in the db if changed
		refs2 = []			# list of refs that cannot be stored directly
		# we first try to store the refs that we can store without modifying the identifiers
		for ref in self:
			identifier = ref.Identifier
			if identifier in old2New.keys():
				self.__changeIdentifier(ref,old2New[identifier])	# change to the new identifier in the text if already done for the
				continue											# same identifier
			ref_id = self.db.getRefFromIdentifier(identifier,('Id',))
			if not ref_id:	# the identifier is not in the database => we must store it
				tmpref = [ getattr(ref,field) for field in OO_BIB_FIELDS ]
				tmpref.insert(0,None)		# unknow Id
				tmpref.append( '' )			# no Abstract in OOo
				tmpId = self.db.writeRef(tmpref)
				if tmpId != None:
					newIdentifier = self.db.getRef(tmpId,('Identifier',))[0][0]
					if newIdentifier != identifier:	# the identifier was in the db and dbBibBase.py has changed it
						old2New[identifier] = newIdentifier
						ref.Identifier = newIdentifier	# change to the new identifier in the text
					newKeys.append(newIdentifier)
		if self.bib != None: self.updateIndex()		# we update to take into account the new identifiers
		else: self.model.getTextFields().refresh()	# otherwise, just refresh the fields
		return newKeys

	def finalize(self):
		msg = ProgressWin()
		try:
			bibOOoPlus.finalize(self,msg.Update)
			msg.Destroy()
		except bibOOo_IOError:
			msg.Destroy()
			ret = wx.MessageBox(_("You must first save the current document before using this function.\n Should I save it and proceed?"),_("Warning"),style = wx.YES_NO|wx.ICON_ERROR)
			if ret == wx.NO:	return
			try:
				self.saveDoc()
				self.finalize()
			except bibOOo_IOError:
				url = wx.FileSelector('Save as...',default_extension='odt',wildcard="%s (*.odt)|*.odt|%s (*.sxw)|*.sxw|%s (*.*)|*.*"%(_("OpenDocument Text"),_("OpenOffice.org Text Document"),  _("All files")),flags=wx.SAVE|wx.OVERWRITE_PROMPT)
				if url == '':
					return
				else:
					self.saveDoc(url)
					self.finalize()
	
	def updateRef(self):
		"""We redefine messages since now we can use wxPython widgets"""
		bibOOoPlus.updateRef(self,messages = lambda x:wx.LogWarning(x))

class ProgressWin(wx.ProgressDialog):
	def __init__(self):
		wx.ProgressDialog.__init__(self,_('Finalize'),_('Finalizing the current document'),maximum=100,style = wx.PD_AUTO_HIDE|wx.PD_APP_MODAL|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME)

	def Update(self,value,message):
		wx.ProgressDialog.Update(self,value*100,message)

