#!/usr/bin/python
# Copyright 2004 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.
#
# generated by wxGlade 0.2 on Sun Jan 19 17:41:27 2003
import os, sys, gettext, locale, ConfigParser, csv
#
if not hasattr(sys, 'frozen'):			# we check if we are not freezed using cx_freeze since wxversion
	try:								# does not work with freezed scripts
		import wxversion				# multiversion install
		#wxversion.select('2.6')
		wxversion.ensureMinimal('2.8')	# we require version 2.8 since bibus 1.5
	except ImportError:
		pass
#


# define 'emptyPath' exception class
# needed for correctly handling exceptions raised upon nonexisting paths
# in Bibus configuration file
# Martijn Werts, 2009-07-06

class emptyPath(Exception):
	"""Class for signalling the absence of certain pathnames in Bibus configuration file"""
	pass

import wx
#print wx.VERSION
from wx.html import HtmlEasyPrinting
#
# setting some environment variables from Setup/bibus.cfg or default
# getting directory of the source
if not hasattr(sys, 'frozen'):			# we check if we are not freezed using cx_freeze
	fileName = sys.argv[0]
else:
	fileName = sys.path[0]
while os.path.islink(fileName): fileName = os.path.realpath(fileName)
sourcedir = os.path.abspath(os.path.dirname(fileName))
cp=ConfigParser.ConfigParser()
# system wide default if it exists (linux) or look in Setup/ directory
cp.read( os.path.join(sourcedir,'bibus.cfg') )
APPNAME=u'bibus'
try:
	localedir = cp.get('PATH','localedir')
	if not localedir: raise emptyPath
except (ConfigParser.NoOptionError,emptyPath):
	localedir = os.path.join(sourcedir,'locale')
try:
	licencepath = cp.get('PATH','licence')
	if not licencepath: raise emptyPath
except (ConfigParser.NoOptionError,emptyPath):
	licencepath = os.path.join(sourcedir,'Docs','copying')
#
# Setting translation
try:
	lang = cp.get('LANG','language')	# if it is defined in bibus.cfg we use it
	os.environ['LANG'] = lang
except (ConfigParser.NoSectionError,ConfigParser.NoOptionError):
	lang =''
try:
	locale.setlocale(locale.LC_ALL,lang)
	presLan = gettext.translation(APPNAME, localedir, locale.getlocale(), fallback=True)	# language from locale
	presLan.install(unicode=True)						# activate language
except:
	locale.setlocale(locale.LC_ALL,'C')
	gettext.install(APPNAME,unicode=True)	# we just install _( in the general name space
#presLan._charset='UTF-8'
#locale = wx.Locale()
#
# getting doc path, according to locale setting
try:
	localeCode = locale.getlocale()[0].split('_')[0]
except:
	localeCode = 'en'
try:
	docdir = cp.get('PATH','docdir')
	if not docdir: raise emptyPath
except (ConfigParser.NoOptionError,emptyPath):
	docdir = os.path.join(sourcedir,'Docs','html')
docpath = os.path.join(docdir,localeCode,'bibus_doc.html')	# try to find in the current langage
if not os.path.exists(docpath):
	docpath = os.path.join(docdir,'en','bibus_doc.html')	# default to english
#
import BIBbase
# reading bibus.conf system-wide file
try:
	systemconf = cp.get('PATH','systemconf')
	if not systemconf: raise emptyPath
except (ConfigParser.NoOptionError,emptyPath):
	systemconf = os.path.join(sourcedir,'bibus.config')		# don't use bibus.conf because of a clash with wx.ConfigBase
try:
	execfile(systemconf)
except:
	pass
# saving some environment variables from Setup/bibus.cfg or default
BIBbase.LOCALEDIR = localedir
BIBbase.SOURCEDIR = sourcedir
BIBbase.DOCPATH = docpath
BIBbase.LICENCEPATH = licencepath
oopath = cp.get('PATH','oopath')
if os.path.isabs(oopath):
	BIBbase.OOPATH = oopath
else:
	BIBbase.OOPATH = os.path.abspath( os.path.join(BIBbase.SOURCEDIR,oopath) ) # the path is relative to bibus install directory (needed portable version)
#
class Bibus(wx.App):
	def OnInit(self):
		wx.InitAllImageHandlers()
		self.SetAppName(APPNAME)
		# reading and eventually converting the config file
		if os.path.isfile( wx.StandardPaths.Get().GetUserDataDir() ):	# old config file in $HOME/.bibus
			BIB.SHORTFILE = []						# removed from BIB => We create them for the conversion
			import BibConfig_old
			oldconf = BibConfig_old.BibConfig(APPNAME)	# we read the old config data
			oldconf.readConfig()
			styles = oldconf.readStyles()
			# we have read everything, we can now delete the old config file and create the new one
			oldconf.DeleteAll()
			del(oldconf)
			import BibConfig
			BIB.CONFIG = BibConfig.BibConfig(APPNAME)	# config file
			# now that the new config dir has been created and we can transfer styles and shortcuts
			BibConfig_old.moveStyles(styles)			# We now store the styles in $HOME/.bibus/Styles/
			if BIB.SHORTFILE:
			    BibConfig_old.moveShortcuts(BIB.SHORTCUTS,BIB.SHORTFILE)	# idem for shortcuts => $HOME/.bibus/Shortcuts/
		else:
			import BibConfig
			BIB.CONFIG = BibConfig.BibConfig(APPNAME)	# config file
			BIB.CONFIG.readConfig()				# read the config file
		wx.Config.Set( BIB.CONFIG )			# we register our config file
		#Do not delete these lines. Useful for debugging
		#It will print the error in the file.
		#fsock = open('out.log', 'w')
		#sys.stderr = fsock
  		# firstStartWizard if needed
		if BIB.FIRST_START: 	# if first start of bibus
			if sys.platform.startswith('darwin'):
				wx.MessageBox(_("""You are using Mac OS X and are running Bibus for the very first time.\n
You will need to set up all configuration files by hand, since no First Start Wizard is currently available.\n
Bibus on Mac OS X is still experimental. Use at your own risk."""),_("Bibus running on Mac OS X"),wx.OK)
			else:
 				self.RunFirstStart()
		elif BIB.CONFIG_VERSION != BIB.BIBUS_VERSION: # if new version
			if sys.platform.startswith('darwin'):
				wx.MessageBox(_("""You are using Mac OS X and have installed a new Bibus version.\n
I cannot automatically update your configuration files, since no First Start Wizard is available at present.\n
You need to do this by hand. Continue at your own risk."""),_("Bibus running on Mac OS X"),wx.OK)
			else:
				wx.MessageBox(_("""You seem to have installed a new version of Bibus.\n 
The First Start Wizard will be run in order to update your Bibus application data.\n
Normally you can click on OK/Next in all steps, unless you want to change your settings."""),_("New Bibus version detected"),wx.OK)
				self.RunFirstStart()
		return 1
	
	def RunFirstStart(self):
		import FirstStart.FirstStart
		dlg = FirstStart.FirstStart.FirstStart(None)			# help to setup a sqlite database
		try:										# not possible for mysql
			dlg.Run()
		finally:
			dlg.Destroy()

# end of class Biblio
#
#
#if __name__ == "__main__":
# we now use BIB instead of BIBbase
# BIB is a copy of the current BIBbase
# this is to avoid modifications of the values
# when reading config file and during program run
import BIB
Bibus = Bibus()
BIB.PRINTER = HtmlEasyPrinting()

# some additional init that have to be done
for field,name in BIB.NAME_FIELD.iteritems():	# see the note in BIBBase
	BIB.FIELD_NAME[name] = field
for typ,name in BIB.NAME_TYPE.iteritems():	# see the note in BIBBase
	BIB.TYPE_NAME[name] = typ

# we read the list of journal abbreviations
# new format since bibus1.5 => simple csv file
# journals can be used uthing any of the abbreviation as key
# we put the key in uppercase to be case insensitive
localjpath = os.path.join(wx.StandardPaths.Get().GetUserDataDir(),'Data',BIB.JOURNAL_FILE)
if os.path.exists(localjpath):
	# we read a user data file in $HOME/.bibus/Data/journals.csv or ...\Application Data\bibus\Data\journals.csv
	f = localjpath
else:
	# system wide data in /usr/share/bibus/Data/journals.csv
	f = os.path.join(BIB.SOURCEDIR,'Data',BIB.JOURNAL_FILE)
fi = file(f)
for line in csv.reader(fi):
	try:
		BIB.JOURNAL[line[0].upper()] = line
		BIB.JOURNAL_ALTERNATE[line[0].upper()] = \
		BIB.JOURNAL_ALTERNATE[line[1].upper()] = \
		BIB.JOURNAL_ALTERNATE[line[2].upper()] = \
		line[0].upper()
	except:
		continue
try: del BIB.JOURNAL_ALTERNATE[""]
except KeyError: pass
fi.close()

# images must be initialized after wx.App
# RefList images
import images
BIB.ARROWS = wx.ImageList(16, 16)
BIB.ARROW_UP = BIB.ARROWS.Add(images.getSmallUpArrowBitmap())
BIB.ARROW_DN = BIB.ARROWS.Add(images.getSmallDnArrowBitmap())
# KeyTree images
import imagesKeyTree
BIB.IMAGESKEY = imagesKeyTree.getImageList()
# create top window
import BibFrame		# we must import now after BIBbase values have been set
bibframe1 = BibFrame.BibFrame(None, -1, BIB.TITLE, name=APPNAME)
Bibus.SetTopWindow(bibframe1)
bibframe1.Show(1)

# if 'multi' key tree view then cycle through different pages 
# to work around wx MS-Windows XP GUI redraw problem
# not tested yet if really working under WinXP
# but this patch does not affect normal operation, and is thus harmless
if BIB.MULTI_USER and sys.platform.startswith('win'):
	bibframe1.keytree.nb_keytree.SetSelection(1)
	bibframe1.Refresh()
	bibframe1.Update()
	bibframe1.keytree.nb_keytree.SetSelection(0)
	bibframe1.Refresh()
	bibframe1.Update() 
	bibframe1.keytree.nb_keytree.SetSelection(1)
	bibframe1.Refresh()
	bibframe1.Update()
	bibframe1.keytree.nb_keytree.SetSelection(0)
	bibframe1.Refresh()
	bibframe1.Update() 

#
Bibus.MainLoop()

		
